$setPristine() 无法以 angular material 形式工作

$setPristine() not working in angular material form

我正在 angular material 中制作一个简单的表格来添加一个 post,我还有一个取消按钮来清除表格。我尝试使用 $setPristine() 但在调用 clearForm 函数后输入字段仍然显示为红色。我遵循了此处的一些答案,但这并没有解决我的问题。 这是我的 index.html 和 app.js

<form id="addForm" name="myForm">
                <fieldset id="addField">
                    <legend id="addFormLegend">Create Post</legend>
                    <md-input-container class="md-block">

                        <md-icon md-svg-src="name.svg"></md-icon>
                        <input ng-model="post.name" type="text" placeholder="Name" ng-required="true">
                    </md-input-container>
                    <md-input-container class="md-block">

                        <md-icon md-svg-src="desc.svg"></md-icon>
                        <input ng-model="post.desc" type="text" placeholder="Description" ng-required="true">
                    </md-input-container>
                    <md-input-container class="md-block">

                        <md-icon md-svg-src="link.svg"></md-icon>
                        <input ng-model="post.url" type="url" placeholder="Url " ng-required="true">
                    </md-input-container>
                    <md-button ng-click="clearForm()" class="md-raised md-primary" id="cancelButton"> Cancel </md-button>
                    <md-button ng-click="createPost(post)" class="md-raised md-primary" ng-disabled="myForm.$invalid" id="addButton"> Add Post </md-button>
                </fieldset>

            </form>

app.controller('mainCtrl', ['$scope', '$firebaseArray', 'posts', function ($scope, $firebaseArray, posts) {
        $scope.posts = posts;
        $scope.showForm = false;
        var defaultForm = {
            name: "",
            desc: "",
            url: ""
        };
        $scope.demo = {};
        $scope.post = angular.copy(defaultForm);

        $scope.createPost = function (post) {
            $scope.posts.$add({
                name: post.name,
                desc: post.desc,
                url: post.url
            });
            $scope.post = {};
        };
        $scope.showAddForm = function () {
            $scope.showForm = true;
        };
        $scope.clearForm = function () {
            // $scope.showForm = false;
            $scope.myForm.$setPristine();
            $scope.post = angular.copy(defaultForm);
            console.log('empty');


        }
    }]);

尝试在控制器的作用域上创建一个属性,例如 $scope.form = null;,然后将表单的名称更改为 form.myForm。然后你应该可以从控制器调用 $scope.form.myForm.$setPrestine()

这是因为表单创建了自己的作用域,并没有直接添加到控制器作用域中。

但是现在您正在创建一个 属性 form 表单控制器分配给它,它又可以从控制器依次访问。

实际上我回答了很多问题,但 none 还在工作。然后我确实在 app.js

中添加了这些行
 $scope.clearForm = function () {
            $scope.showForm = false;
            $scope.myForm.$setPristine();
            $scope.myForm.$setUntouched();
            $scope.post = {};
 }

所以基本上在 $setPristine() 对我有用之后添加 $scope.myForm.$setUntouched();