0

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.

User 101
  • 1,351
  • 3
  • 12
  • 18

1 Answers1

2

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

David
  • 3,787
  • 2
  • 29
  • 43