AngularJS ng-repeat和表单验证

时间:2013-06-06 15:54:10

标签: javascript angularjs angularjs-ng-repeat

我在AngularJS中遇到表单验证问题,并在表单中使用了ng-repeat的项目。

HTML:

<div ng-app>
    <div ng-controller="EditController">
        <form name="form" novalidate>Name:
            <br/>
            <input type="text" ng-model="model.name" required="" />
            <hr />Products:
            <br/>
            <div ng-repeat="product in model.products">
                <div>
                    <input type="text" ng-model="product.name" required="" />
                    <input type="text" ng-model="product.price" required="" /> <a href="javascript:void(0)" ng-click="remove($index)">Remove</a>

                </div>
            </div>
            <hr />
            <button ng-disabled="form.$invalid || !form.$dirty" ng-click="save()">save</button>
            <div ng-show="form.$invalid && !form.$pristine">There are errors.</div>
            <div ng-show="!form.$dirty && form.$pristine">No changed detected to be saved.</div>
            <div>
                <p>Dirty? {{form.$dirty}}</p>
                <p>Invalid? {{form.$invalid}}</p>
                <p>Pristine? {{form.$pristine}}</p>
            </div>
        </form>
    </div>
</div>

JS:

function EditController($scope) {
    $scope.model = {
        name: "Phil",
        products: [{
            name: "Foo",
            price: 12.99
        }, {
            name: "Bar",
            price: 15.99
        }, {
            name: "FooBar",
            price: 24.99
        }]
    };

    $scope.remove = function(index){
      $scope.model.products.splice(index, 1);  
    };

    $scope.save = function () {
        console.log("saved");
    };
}

小提琴:

http://jsfiddle.net/66V6m/2/

复制:

单击删除删除1项,表单不会变脏,因此按钮无法启用。

如果您编辑名称字段,则表单会变脏。

关于如何从数组中删除项目的任何想法都会使表单变脏?

2 个答案:

答案 0 :(得分:11)

Angular提供$setDirty()功能,仅用于您在此处尝试完成的目的。只需将其添加到您的ng-click属性中,就像这样

<input type="text" ng-model="product.price" required="" /> 
<a href="javascript:void(0)" ng-click="remove($index); form.$setDirty(true);">Remove</a>

我已经分道扬琴,让它工作here

答案 1 :(得分:2)

这是一种方式。

$scope.remove = function (index) {
    $scope.model.products.splice(index, 1);
    $scope.form.$dirty = true;
};