setPristine不是一个函数

时间:2016-08-09 18:49:54

标签: angularjs

我的角度形式全部设置和工作。在调用对json请求的响应后设置这些值。表单已成功填充json响应。之后我想重置'表单,如$ scope.object。$ setPristine。但我得到一个错误:

$scope.object.$setPristine is not a function

我使用 angular 1.4.8

这是我的HTML:

<div ng-app="myApp" ng-controller="formController" class="ng-scope">
    <form name="object" ng-submit="submit()" method="post" action="" novalidate="" class="ng-pristine ng-valid">
        <div class="form-group">
            <label class="control-label" for="object_name">Name</label>
            <input type="text" id="object_name" name="object[name]" ng-model="object.name" class="form-control ng-pristine ng-valid ng-touched" value="Object 2c">
        </div>
        <div class="form-group">
            <label class="control-label" for="object_elements">Elements</label>
            <select id="object_elements" name="object[elements][]" ng-model="object.elements" ng-options="opt.id as opt.name for opt in options | orderBy: &quot;id&quot;" class="form-control ng-pristine ng-untouched ng-valid" multiple="multiple"></select></div>
        <div class="form-group">
            <input ng-disabled="object.$pristine" class="btn btn-primary" value="Save" ng-click="submitForm()">
        </div>
    </form>
</div>

这是我的.js:

    var app = angular.module('myApp', ["ngResource"]).controller('formController', function ($scope, $http, $location) {

    var url = $location.absUrl() + '/json'

    $http({
        method: 'GET',
        url: url
    }).then(function (response) {
        $scope.status = response.status;
        $scope.data = response.data;
        $scope.object = response.data;
        $scope.object.$setPristine();
        $('#modal-loading').modal('hide');

    }, function (response) {
        $scope.data = response.data || "Request failed";
        $scope.status = response.status;
        $('#modal-loading').modal('hide');
    });
});

2 个答案:

答案 0 :(得分:1)

您使用JSON响应覆盖$scope.object,当然它没有附加任何功能。

$scope.object = response.data;
$scope.object.$setPristine();

这在功能上与:

相同
$scope.object = {of_course: "this doesn't work"};
$scope.object.$setPristine();

您可能只需要将ng-model更改为引用$scope.data而不是$scope.object

ng-model="data.name"

然后不会覆盖您的表单对象。

答案 1 :(得分:0)

我的方式是......

<form name="newClntForm" id="newClnt" class="add(newClnt, newClntForm)">
<input type="text" class="form-control" ng-model="newClnt.name" placeholder="Contact Person Name" required >
</form>

控制器保存功能

function(newClnt, newClntForm){
    angular.copy({},newClnt);
    // newClntForm is form name
    newClntForm.$setPristine();
    newClntForm.$setUntouched();
};