AngularJS:ng-repeat中的SetValidity

时间:2013-12-09 20:00:09

标签: angularjs

我想检查一个输入值是否有效,(如果有人花了至少25美分来自糖果列表中的糖果),如果没有,则将该输入标记为$ invalid,因此表单不会提交。

<form novalidate name="candyForm">
    <div ng-repeat="candy in candies">
        <input name="candyCost" type="text" ng-model="candy.cost" required>
        <div class="error" ng-show='checkEnoughMoney()'>You only have 1 dollar to spend</div>
        <div class="error" id="candyError{{$index}}">You must spend at least 25c per candy</div>
    </div>
</form>

checkEnoughMoney()是:

$scope.checkEnoughMoney = function() {
    var total = 0;
    for(var i = 0; i < $scope.candies.length; i++) {
        var amount = parseFloat($scope.sweets[i].cost) || 0;
        total = total + amount;
        if((parseFloat(amount) >= 25) && (parseFloat(amount) <= 100)) {
            $("#candyError" + i).hide();
        }
        else {
            $("#candyError" + i).show();
        }
    }
    if(total > 100) {
        $scope.candyForm.candyCost.$setValidity('candyForm.candyCost',false);
        return true;
    }
    else {
        $scope.candyForm.candyCost.$setValidity('candyForm.candyCost',true);
        return false;
    }
};

将$ scope.candyForm.candyCost设置为true或false在这里工作,因为它影响所有实例,如果糖果,这是伟大的,它需要。但是,如果该人输入的分数低于25美分或超过100美分,如何使单一实例无效?

正如您所看到的,我已经作弊使得25&gt; = cost&gt; = 100条消息会显示,但表单仍在提交,因为输入未设置为无效。如果我尝试$ scope.candies [index] .setValidity(“cost”,false),则会抛出错误,因为父作用域无法访问ng-repeat内的作用域。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

以下是处理Angular中应该处理问题的表单的示例。

http://docs.angularjs.org/cookbook/advancedform

我更喜欢设置一个控制器fn来处理请求并通过服务传递它们。