【问题标题】:How to listen to scope events in Angular 1.5 component?如何在 Angular 1.5 组件中监听范围事件?
【发布时间】:2017-01-02 15:51:44
【问题描述】:

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

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, toState, toParams) => {
            //logic goes here
        });
    }
}

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

编辑:

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

【问题讨论】:

  • @georgeawg 我对这里的 $on 而不是 $watch 的替代品感兴趣,因为 $onChange 可以在您只是观察变量时替换 $on。我想听范围事件,因为不是 100% 的 Angular 1.3 代码可以迁移到 1.5,我仍然有触发范围事件的指令!
  • 在作用域上触发事件的替代方法是使用表达式绑定将事件从组件传递到父组件。并使用单向绑定将事件以另一种方式从父组件传递到子组件。
  • @georgeawg 但父母仍然必须收听范围事件?有什么方法可以让我不使用 $scope.$on 并且仍然收听路由更改事件?或任何其他由 $rootscope 上的第三方组件触发的事件?

标签: javascript angularjs ecmascript-6 angularjs-1.5 angular-components


【解决方案1】:

作用域事件可以转换为服务中的 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 的简单迁移路径。

DEMO on PLNKR

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2016-10-02
    • 2021-11-02
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多