AngularJS无法读取属性' $ setPristine'未定义的

时间:2015-09-03 06:42:12

标签: javascript angularjs

我收到错误无法读取属性' $ setPristine'尝试重置表单时未定义。

我的控制器:

formApp.controller('FormController', ['$scope', 
    function ($scope) {

        $scope.options = ["Opt1", "Opt2", "Opt3", "Other"];
        $scope.formData = {
            selectedOption: null,
            firstName: "",
            lastName: "",
            email: "",
            phone: "",
            fax: "",
            comments: ""
        };

        var origData = angular.copy($scope.formData);


        $scope.submit = function () {
            // submit code goes here
        };

        $scope.reset = function () {
            $scope.formData = angular.copy(origData);

              //  $scope.financeForm.$setUntouched();
                $scope.financeForm.$setPristine();


        };

        $scope.reset();

    }
]);

我的HTML(我已经删除了大多数字段以保持最小化):

<form id="financeForm" name="financeForm" ng-submit="financeForm.$valid && submit()" novalidate>
    <md-content layout-padding class="autoScroll">
        <md-input-container flex md-is-error="financeForm.selectedOption.$invalid && (financeForm.$submitted || financeForm.selectedOption.$dirty)">
            <md-select required placeholder="Nature of your Enquiry" ng-model="formData.selectedOption" name="selectedOption" id="selectedOption">
                <md-option ng-repeat="opt in options" value="{{opt}}">{{opt}}</md-option>
            </md-select>
            <div ng-messages="financeForm.selectedOption.$error" ng-if="financeForm.$submitted || financeForm.selectedOption.$touched">
                <div ng-message="required">Please your enquiry option.</div>
            </div>
        </md-input-container>

        <md-input-container>
            <label>Comments</label>
            <textarea ng-model="formData.comments" columns="1" md-maxlength="500"></textarea>
        </md-input-container>
    </md-content>

    <md-button class="md-raised" ng-click="reset();">RESET</md-button>
    <md-button class="md-raised md-primary">SUBMIT</md-button>
</form>

我不知道自己做错了什么。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

$ setPristine未定义,因为你需要将它作为服务添加到顶部的函数

function ($scope,$setPristine){...

这会让函数知道$ setPristine

的含义

此外,角度JS $ setPristine仅适用于angularjs 1.1。*,请检查您的版本。

答案 1 :(得分:0)

检查在创建表单之前呈现页面的任何打开函数调用,这可能最终导致“$ setPristine is undefined” 通过使用此代码,您可以将$ dirty,$ name,$ untouched,$ pristine,$ valid等重置为其原始布尔状态。 在HTML代码中

<md-button ng-click="reset(ExampleForm)">Cancel</md-button>
<md-button type="submit" ng-disabled="ExampleForm.$invalid || !ExampleForm.$dirty">Save</md-button>

在控制器中

    $scope.reset = function(formName){
        formName.$setPristine();
    };