7

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

角 1.3

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

角 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
});

编辑:

对这里的 $on 而不是 $watch 的替代品感兴趣,因为 $onChange 可以在您只是观察变量时替换 $watch。我想听范围事件,因为不是 100% 的 angular 1.3 代码可以迁移到 1.5,我仍然有触发范围事件的指令!

4

1 回答 1

3

范围事件可以转换为服务中的 RX observables。

 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 的简单迁移路径。

PLNKR 上的演示。

于 2016-08-28T20:28:15.137 回答