sergioFC
sergioFC

Reputation: 6016

checking function when model changes in other instance of the directive?

In angularjs I have made this simple example with two inputs. I want to change the background color of a input to green if its value its equal to 'green'. This example works, (it changes the background of a input if its value its equal to 'green'), but I have noticed (using js console) that when I change the value of any of the two inputs angularjs calls (both) the functions that check if the value its equal to 'green'.

<div ng-app="myApp">
    <div ng-controller="myController">
        <my-input identifier="id1" />
    </div>
    <div ng-controller="myController">
        <my-input identifier="id2" />
    </div>
</div>



angular.module('myApp', []).directive('myInput', function() {
    return {
        restrict: 'E',
        scope: {
            identifier: '='
        },
        template: '<input type="text" ng-class="{greenBackground: identifier.checkIfGreen()}" ng-model="identifier.value"/>'
    };
}).controller('myController', ['$scope',

    function($scope) {
        $scope.id1 = {
            value: '',
            checkIfGreen: function() {
                console.log('First value checked');
                return this.value == 'green'
            }
        }
        $scope.id2 = {
            value: '',
            checkIfGreen: function() {
                console.log('Second value checked');
                return this.value == 'green'
            }
        }

    }
]);

Why is this happening? Is there a way to avoid the call to check if the second inputs is equal to 'green' if I just change the value of the first input.

Fiddle

Note: this is just an example, I know there much are better ways of getting this simple behavior.

Upvotes: 1

Views: 70

Answers (1)

zs2020
zs2020

Reputation: 54543

Because functions in ng-class will be evaluated for every digest cycle if there is any model change happening. Since there are 2 ng-classs defined in the page so both checkIfGreen()s are evaluated every time if there is model change going on.

You use ng-change to call the function and assign the returned value to a temporary variable like this:

template: '<input type="text" 
                  ng-class="{greenBackground: flag}" 
                  ng-change="flag=identifier.checkIfGreen()" 
                  ng-model="identifier.value"/>'

Demo: http://jsfiddle.net/pvrcy5cL/

Upvotes: 1

Related Questions