javascript - 当指令的其他实例中模型发生变化时检查函数?

标签 javascript angularjs angularjs-scope

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

    }
]);

为什么会发生这种情况?如果我只是更改第一个输入的值,有没有办法避免调用检查第二个输入是否等于“绿色”。

<强> Fiddle

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

最佳答案

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

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

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

演示:http://jsfiddle.net/pvrcy5cL/

关于javascript - 当指令的其他实例中模型发生变化时检查函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26188070/

相关文章:

javascript - AngularJS : How to pass an object from the directive to transcluded template

javascript - 最初搜索视频后无法快退或前进?

javascript - function/node-red 中的多个输入

javascript - 在单行中声明多个变量 + Angular 2 和 TypeScript

javascript - 如何以编程方式使用 AngularJS 提交表单

angularjs - 使用 ui 路由器的范围和 Controller 实例化

Javascript:如果 a 是数组中的值,如何编写

javascript - PHP如何捕获浏览器窗口关闭事件?

javascript - Angular Chosen 默认选择不起作用

javascript - AngularJS 中跨隔离范围的链接表达式绑定(bind)