In what order are angular observers and event listeners executed?

If you first change the scope property and then broadcast the second event, will the corresponding callback and event listener be called back in the same order? For example:

$scope.foo = 3;
$scope.$broadcast('bar');

and in another place:

$scope.$watch('foo', function fn1(){...});
$scope.$on('bar', function fn2(){...});

Will it fn1always be executed before fn2, or vice versa, or can it not rely on the order? Please indicate sources, preferably official angular docs.

In case it matters: let's say $ scope.foo = and broadcast $ happen in a function called by ng-click (i.e. user interaction)

[aside] Sorry, the title of the question is sloppy - rename if you have something better.

+4
1

, , Angular $digest $emit $broadcast.

, , Angular - . Angular, (. ).

, , , , . , .

...

template.html

<div ng-app="myApp">
  <div watch-foo ng-controller="FooController">
    <button ng-click="changeFoo()">
      Change
    </button>
  </div>
</div>

script.js

angular.module('myApp', [])
  .directive('watchFoo', watchFooDirective)
  .controller('FooController', FooController);

function watchFooDirective($rootScope) {
  return function postLink(scope) {
    scope.$watch(function () {
        return scope.foo;
    }, function (value) {
        console.log('scope.$watch A');
    });
    scope.$on('foo', function (value) {
        console.log('scope.$on A');
    });
    $rootScope.$on('foo', function (value) {
        console.log('$rootScope.$on A');
    });
    $rootScope.$on('foo', function (value) {
        console.log('$rootScope.$on B');
    });
    scope.$on('foo', function (value) {
        console.log('scope.$on B');
    });
    scope.$watch(function () {
        return scope.foo;
    }, function (value) {
        console.log('scope.$watch B');
    });
  };
}

function FooController($scope) {
  $scope.foo = 'foo';
  $scope.changeFoo = function() {
    $scope.foo = 'bar';
    $scope.$emit('foo');
  };
}

... "":

scope.$on A
scope.$on B
$rootScope.$on A
$rootScope.$on B
scope.$watch A
scope.$watch B

UPDATE

, , , : https://jsfiddle.net/sscovil/ucb17tLa/

, watch, : https://jsfiddle.net/sscovil/sx01zv3v/

, .

+4

Source: https://habr.com/ru/post/1622137/


All Articles