User 101
User 101

Reputation: 1431

unable to update controller variable from directive

I have a directive:

app.directive('hideButton', function () {
    return {
        restrict: "A",
        scope: {
            init: '='
        },
        replace : true,
        link: function(scope, elem, attrs) {
           if(scope.init) {
                elem.css('display', 'none');
                scope.init = false;
            }

            elem.on('click', function() {
                elem.css('display', 'none');
            });
        }
    }
});

Here, init is a controller variable.

Now in the directive I have set scope.init = false but the change is not reflected into controller.

Upvotes: 0

Views: 271

Answers (1)

David
David

Reputation: 3937

This is a common problem in AngularJS, because this is just unintuitive.

If you bind a primitive type into your directive (init of type boolean in this case), the binding gets lost. Try wrapping it into an object

{ value: true }

In your controller.

Your directive now becomes

if (scope.init.value) {
    elem.css('display', 'none');
    scope.init = false;
}

Your question is also answered here: https://stackoverflow.com/a/29265539/537738

Upvotes: 2

Related Questions