Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator for Scope

Is it possible, and if so how, to decorate $scope so all scopes have some extra function / property?

I'm trying to do this:

$provide.decorator('$scope', function($scope)
{
    $scope.cakes = true;
    return $scope;
});

But it explodes with:

Unknown provider: $scopeProvider from App.

I know I can add properties and functions to the $rootScope and it will prototypically inherit, but I want isolated scopes in directives to also have access to these added things.

like image 717
Duncan Matheson Avatar asked Jan 13 '23 09:01

Duncan Matheson


1 Answers

I had the same problem.

Just extend $rootScope prototype. Then isolated scopes will also have this method.

This is my attempt to use lodash debounce function as native scope method:

angular.module('Test', [])
.config(function($provide) {
    $provide.decorator('$rootScope', function ($delegate) {
        $delegate.__proto__.$$busy = 0;
        $delegate.__proto__.$watchDebounce = function (watchExpression, listener, objectEquality){
            var _scope = this;
            var debouncedListener = _.debounce(function (newValue, oldValue, scope){
                listener(newValue, oldValue, scope);
                _scope.$$busy = 0;
                scope.$digest();
            }, 1000);

            var wrappedListener = function (newValue, oldValue, scope){
                _scope.$$busy = 1;
                debouncedListener(newValue, oldValue, scope);
            }

            return this.$watch(watchExpression, wrappedListener, objectEquality);
        }
        return $delegate;
    })
})

Working example here http://jsfiddle.net/3ncct/

like image 184
Dimac Avatar answered Jan 17 '23 18:01

Dimac