質問

In general terms

Can I make it so that all controllers have a watcher that exposes a local scope variable or a method that affects only local scope? Kind of like traits.

More specifically

Out of the box I want each new controller to have a status property available and set on its own scope and a watcher that queries a service to set the status. The watcher would pass the name of the controller and receive information back about itself.

In my case, the service is a layer on top of $http that simply keeps track of which parts of the application are making which requests.

Optionally, I would like to restrict this functionality to controllers that inject this particular service.

役に立ちましたか?

解決

Scope Decorator: $onRootScope

Decorates the $rootScope with an $onRootScope method as suggested here

app.config(['$provide', function($provide){
    $provide.decorator('$rootScope', ['$delegate', function($delegate){

        // [Object.defineProperty()][2]
        // To make sure the $onRootScope property doesn't show up unexpected when enumerating over $scope we use `Object.defineProperty()` and set enumerable to false. Keep in mind that you might need an ES5 shim.

        Object.defineProperty($delegate.constructor.prototype, '$onRootScope', {
            value: function(name, listener){
                var unsubscribe = $delegate.$on(name, listener);
                this.$on('$destroy', unsubscribe);
            },
            enumerable: false
        });

        return $delegate;
    }]);
}]);

References

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top