AngularJS : How to watch service variables?

后端 未结 21 1815
盖世英雄少女心
盖世英雄少女心 2020-11-22 09:12

I have a service, say:

factory(\'aService\', [\'$rootScope\', \'$resource\', function ($rootScope, $resource) {
  var service = {
    foo: []
  };

  return          


        
21条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:36

    I have found a really great solution on the other thread with a similar problem but totally different approach. Source: AngularJS : $watch within directive is not working when $rootScope value is changed

    Basically the solution there tells NOT TO use $watch as it is very heavy solution. Instead they propose to use $emit and $on.

    My problem was to watch a variable in my service and react in directive. And with the above method it very easy!

    My module/service example:

    angular.module('xxx').factory('example', function ($rootScope) {
        var user;
    
        return {
            setUser: function (aUser) {
                user = aUser;
                $rootScope.$emit('user:change');
            },
            getUser: function () {
                return (user) ? user : false;
            },
            ...
        };
    });
    

    So basically I watch my user - whenever it is set to new value I $emit a user:change status.

    Now in my case, in the directive I used:

    angular.module('xxx').directive('directive', function (Auth, $rootScope) {
        return {
            ...
            link: function (scope, element, attrs) {
                ...
                $rootScope.$on('user:change', update);
            }
        };
    });
    

    Now in the directive I listen on the $rootScope and on the given change - I react respectively. Very easy and elegant!

提交回复
热议问题