Mr Smith
Mr Smith

Reputation: 3486

How can I reinitialize an Angular directive?

I'm using the fcsaNumber directive to check for the validity of numbers entered into an input box. I got this working, but the value im checking for is dynamic, meaning it can change depending upon what options have been selected. It appears this directive only initializes once. what do I need to do to get it to reinitialize when the options have changed?

//this works fine
    <input name="Employees" type="text" ng-model="Input.Employees" fcsa-number="{min: 1}" required="">

//this only inits once, so its not dynamic
    <input name="Employees" type="text" ng-model="Input.Employees" fcsa-number="{{getMin()}}" required="">

Upvotes: 5

Views: 14693

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21485

Rebuilding the whole directive would work, but it's a brute-force solution -- and particularly undesirable for directives like this one that accept user input, which would get blown away were you to re-init the directive.

Instead you can use scope.$watch or attrs.$observe to allow the directive to more readily respond to changes in its attribute values:

module.directive('foo', function() {
    return {
        scope: {
            'bar': '@'
        },
        link: function(scope, element, attrs) {
            scope.$watch('bar', function() {
                // runs when scoped value 'bar' changes
            });
            attrs.$observe('baz', function() {
                // Similar to $watch, but without isolate scope
            });
        }
    }
});

AngularJS : Difference between the $observe and $watch methods has a good explanation of the differences between $observe and $watch.

Upvotes: 8

Alex Johnson
Alex Johnson

Reputation: 1574

You could potentially use ng-if to initialize / tear down the directive in question. (ng-if docs)

The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM - CodeHater

Here's a great stack overflow answer on the differences between ng-if and ng-show.

Upvotes: 7

Related Questions