gpt4 book ai didi

javascript - Angularjs $setPristine 不使用 Controller 作为语法

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:52 36 4
gpt4 key购买 nike

$setPristine 在使用 $scope 引用时工作正常,但似乎不适用于“ Controller 作为语法”

在 View 中:

<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>

<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>

在 app.js 中:

var app = angular.module('plunker', []);

app.controller('FirstCtrl', function() {
'use strict';
var vm = this;
vm.data = { "name": ""};

vm.reset = function() {
vm.data.name = "";
vm.form1.$setPristine();
}
});

app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = { "name": ""};

$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});

这里是 plunker:http://plnkr.co/edit/VcgZx3?p=preview

最佳答案

即使您使用 controller as 语法,表单和其他属性仍然绑定(bind)到范围而不是 Controller 实例,因此您仍然必须使用 $scope.form1.$setPristine (); 设置表单的状态。

var app = angular.module('my-app', [], function() {})

app.controller('FirstCtrl', function($scope) {
'use strict';
var vm = this;
vm.data = {
"name": ""
};

vm.reset = function() {
vm.data.name = "";
$scope.form1.$setPristine();
}
});

app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = {
"name": ""
};

$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>

<div ng-app="my-app">
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr/>

<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
</div>

关于javascript - Angularjs $setPristine 不使用 Controller 作为语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32735447/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com