我正在将代码从 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,我仍然有触发范围事件的指令!