Marco
Marco

Reputation: 2473

Directive not working with ng-if

I have the following directive that works correctly unless i use a ng-if on the containing element as well. What I am trying to do is simply set a dynamic property on the scope with an associated function. The scope does not contain the property (undefined).

any help would be great!

app.directive('stRefresh', function () {
    return {
        require: '^stTable',
        link: function (scope, ele, attr, ctrl) {
            if (attr.stRefresh) {
                var name = attr.stRefresh;
                scope[name] = scope[name] || {};
                scope[name].refresh = function () {
                    return ctrl.search();
                };
            }
        }
    }
});

Upvotes: 0

Views: 2133

Answers (1)

Jack A.
Jack A.

Reputation: 4443

It would be helpful to know what doesn't work, but I suspect that you have been bitten by the problem of nested scopes.

The ng-if directive creates a child scope. When you modify the scope in your directive:

scope[name] = scope[name] || {};

You are modifying the child scope. Due to prototypal inheritance, this does not modify the scope of the parent. Therefore, if you are expecting to see a change in the parent scope, you won't see it.

To fix it, you need to add a dot to the scope reference. Something like this:

scope.data[name] = scope.data[name] || {};
scope.data[name].refresh = function () {
    return ctrl.search();
};

The scope.data property needs to be a reference to an object. Since you are not modifying the reference, you can modify the properties of that object from both parent and child scopes.

Upvotes: 2

Related Questions