javascript – 如何在Angular 1.5组件中监听范围事件?

我正在将代码从Angular 1.3迁移到Angular 1.5组件和ES6控制器.我试图在这里找到一些东西,但没有足够的帮助.关于如何在范围外观看事件所需的建议,而不是下面提到的方式.或者如何从指令触发范围事件.如果存在替代方案,请建议正确的方法.

Angular 1.3

angular
.module('test')
.directive('test',function() {
    return {
        link: function(scope) {
            scope.$on('$stateChangeStart',function(event,toState,toParams) {
                //logic goes here..
            });
        }
    }
});

Angular 1.5 / ES6

class TestController {
    /* @ngInject */
    constructor($scope) {
        this._$scope = $scope;
    }

    $onInit() {
        this._$scope.$on('$stateChangeStart',(event,toParams) => {
            //logic goes here
        });
    }
}

angular
.module('test')
.component('test',{
    controller: TestController
});

编辑:

有兴趣选择$on而不是$watch,因为当你只是观察变量时,$onChange会取代$watch.我想听范围事件,因为不是100%的angular 1.3代码可以迁移到1.5,我仍然有指令触发范围上的事件!

解决方法

范围事件可以转换为服务中的RX可观察对象.
app.factory("rxLocationChangeStart",function($rootScope,rx) {
     var rxLocationChangeStart = new rx.Subject();
     $rootScope.$on("$locationChangeStart",function() {
       rxLocationChangeStart.onNext(arguments);
     });
     return rxLocationChangeStart;
 })

然后组件可以订阅这些事件:

app.component("locationMonitor",{
       scope: {},template: ['<p>oldpath={{$ctrl.oldpath}}</p>','<p>newPath={{$ctrl.newPath}}</p>'].join(''),controller: function (rxLocationChangeStart) {
         var $ctrl = this;
         var subscr = rxLocationChangeStart.subscribe(function(data) {
             console.log("locationChangeStart ",data);
             $ctrl.newPath = data[1];
             $ctrl.oldpath = data[2];
         });
         this.$onDestroy = function() {
           subscr.dispose();
         };
       }
 })

Angular 2用RX Observables替换范围事件总线.将范围事件转换为RX Observables提供了从AngularJS到Angular 2的简单迁移路径.

DEMO on PLNKR.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...