Javascript 在指令的其他实例中更改模型时检查函数?

Javascript 在指令的其他实例中更改模型时检查函数?,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,在angularjs中,我用两个输入做了这个简单的例子。如果输入值等于“绿色”,我想将其背景色更改为绿色。这个例子很有效,(如果输入值等于“绿色”,它会改变输入的背景),但是我注意到(使用js控制台)当我改变两个输入值中的任何一个值时,angularjs调用(两个)函数来检查输入值是否等于“绿色” <div ng-app="myApp"> <div ng-controller="myController"> <my-input identif

在angularjs中,我用两个输入做了这个简单的例子。如果输入值等于“绿色”,我想将其背景色更改为绿色。这个例子很有效,(如果输入值等于“绿色”,它会改变输入的背景),但是我注意到(使用js控制台)当我改变两个输入值中的任何一个值时,angularjs调用(两个)函数来检查输入值是否等于“绿色”

<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'
            }
        }

    }
]);

angular.module('myApp',[])指令('myInput',function(){
返回{
限制:'E',
范围:{
标识符:'='
},
模板:“”
};
}).controller('myController',['$scope',
职能($范围){
$scope.id1={
值:“”,
checkIfGreen:function(){
log(“选中的第一个值”);
返回此值。值==“绿色”
}
}
$scope.id2={
值:“”,
checkIfGreen:function(){
log('第二个值已检查');
返回此值。值==“绿色”
}
}
}
]);
为什么会这样?如果我只是更改第一个输入的值,是否有方法避免调用检查第二个输入是否等于“绿色”


注意:这只是一个例子,我知道有很多更好的方法可以实现这个简单的行为。

因为如果发生任何模型更改,
ng类
中的函数将针对每个摘要周期进行评估。由于页面中定义了2个
ng类
s,因此如果模型发生更改,每次都会对这两个
checkIfGreen()
s进行评估

您可以使用
ng change
调用函数,并将返回值分配给如下临时变量:

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

演示:

“谢谢!这确实解决了调用两个函数的问题,但是当我更改其中一个输入时,angularjs是否检查每个标志的值?我认为,与其这样做,不如在每个变量上使用'watch'或$watch,不是吗?