使用函数检查AngularJs ng-ng

时间:2014-02-11 12:12:08

标签: angularjs

我有一个表单,我正在尝试在输入ng-checked="someFunction()"中使用一个函数,我不知道这是否可行或我做错了什么。我在我的控制器中有功能,我在视野中调用它。至于功能,我认为它肯定工作,ng-checked正在解雇它但返回true或false不会改变任何东西。那么问题是有没有办法在'ng-checked'中使用函数?

    $scope.multiAnswers = function (answers, optionId) {
        angular.forEach(answers, function (answer, key) {
            if (answer.option_choice_id == optionId) {
                return true;
            }
        });

        return false;
    };

2 个答案:

答案 0 :(得分:20)

ng-checked可以使用函数。这是一个演示:

$scope.getCheckedFalse = function(){
    return false;
};

$scope.getCheckedTrue = function(){
    return true;
};

HTML:

<input type="checkbox" ng-checked="getCheckedFalse()"/>
<input type="checkbox" ng-checked="getCheckedTrue()"/>

DEMO

您的问题是,从不在功能结束时返回 true 。在angular.forEach中return true;没有帮助。

尝试:

$scope.multiAnswers = function (answers, optionId) {
     var returnValue = false;
     angular.forEach(answers, function (answer, key) {
         if (answer.option_choice_id == optionId) {
              returnValue = true;
              return;
         }
     });

     return returnValue;
};

看起来我们无法摆脱angular.forEach:Angular JS break ForEach

要在answer.option_choice_id == optionId 为真时立即提高效果。您可以尝试jQuery $.each或使用vanilar javascript(for循环)。

答案 1 :(得分:3)

您需要做的是使用状态变量作为ng-checked表达式,例如:ng-checked="someValue"。然后,您的代码中的其他地方可以更新$scope值。问题是,通过使用一个函数,它实际上不知道它应该更新它的值。