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

Ash*_*wal 7 javascript angularjs ecmascript-6 angularjs-1.5 angular-components

我正在将代码从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..
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Angular 1.5/ES6

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

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

angular
.module('test')
.component('test', {
    controller: TestController
});
Run Code Online (Sandbox Code Playgroud)

编辑:

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

geo*_*awg 3

范围事件可以转换为服务中的 RX 可观察量。

 app.factory("rxLocationChangeStart", function($rootScope, rx) {
     var rxLocationChangeStart = new rx.Subject();
     $rootScope.$on("$locationChangeStart", function() {
       rxLocationChangeStart.onNext(arguments);
     });
     return rxLocationChangeStart;
 })
Run Code Online (Sandbox Code Playgroud)

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

 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();
         };
       }
 })
Run Code Online (Sandbox Code Playgroud)

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

PLNKR 上的演示。