How to listen for scope events in Angular 1.5 component?

I am in the middle of the transition code from Angular 1.3 to Angular 1.5 to ES6 components and controllers. I tried to find something here on SO, but not useful enough. Suggestions for how to watch events in scope other than the methods mentioned below. Or how to trigger scope events from a directive. Also, please suggest the correct way to do this, if there is an alternative.

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

Edit:

Of interest is the alternative to $ on, not $ watch here, because $ onChange can replace $ watch when you just watch variables. I want to listen to sphere events, since not 100% of Angular 1.3 code can be ported to 1.5, I still have directives that trigger events in scope!

+5
source share
1 answer

Area events can be converted to RX-observable in the service.

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

Then the component can subscribe to these events:

  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 replaces the area event bus with RX Observables. Converting scope events to RX Observables provides a simple migration path from AngularJS to Angular 2.

DEMO on PLNKR .

+3
source

All Articles