5

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="">
Mr Smith
  • 3,318
  • 9
  • 47
  • 85

2 Answers2

8

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.

Community
  • 1
  • 1
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
7

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.

Community
  • 1
  • 1
Alex Johnson
  • 1,504
  • 13
  • 20