****注意我删除了一些其他功能,以便更快地读取代码。我无法清除表格。当我点击带有取消功能的按钮时。我以为我可以设置默认表单,但这并没有什么区别。
<form name="myForm" novalidate ng-submit="submit()">
<table class="mealCost">
<!-- descriptions -->
<tr>
<td> Base Meal Price: </td>
<td><input type="number" name="price" ng-model="mealPrice" required></td>
</tr>
<!-- waiter puts in the info -->
<tr>
<td> Tax Rate: % </td>
<td><input type="number" step="0.01" name="tax" ng-model="mealTax" required></td>
</tr>
<tr>
<td> Tip Percentage: % </td>
<td><input type="number" name="tip" step="0.01" ng-model="tipPercent" required></td>
</tr>
</table>
<p class="userResponse">
<input type="submit" value="Submit">
<!-- <input id="cancel" type="submit" value="Cancel" ng-submit="cancel(original)"> -->
<button ng-click="cancel()">Start Over</button>
</p>
</form>
这是我的javascript我试图使用按钮命令将我的表单设置为$ setPristine。我设置默认表单会有所帮助,但提交
时没有任何反应var app = angular.module('myApp',[]).
controller('costController', function($scope) {
// $scope.ready= false;
$scope.mealPrice ="" ;
$scope.mealTax = 0.05;
$scope.tipPercent =0.05;
// possibly could do
var defaultForm={
price: "",
tax: "",
tip:""
}
$scope.cancel = function() {
$scope.myForm.$setPristine();
$scope.user = angular.copy(defaultForm);
console.log('empty');
}
答案 0 :(得分:27)
我认为你错了。
$ setPristine:
&#34;可以调用此方法来删除&#39; ng-dirty&#39; class并将表单设置为其原始状态(ng-pristine类)。此方法还将传播到此表单中包含的所有控件。&#34;
所以这只清除了类而不是$ scope变量。 您确实重置了$ scope.user变量,可以说:
添加&#39;用户。&#39;在Html中的每个模型前面
ng-model="user.tipPercent"
ng-model="user.mealTax"
ng-model="user.mealPrice"
在你的JS中替换它:
// $scope.ready= false;
$scope.mealPrice ="" ;
$scope.mealTax = 0.05;
$scope.tipPercent =0.05;
// possibly could do
var defaultForm={
price: "",
tax: "",
tip:""
}
$scope.cancel = function() {
$scope.myForm.$setPristine();
$scope.user = angular.copy(defaultForm);
console.log('empty');
}
到此:
var defaultForm = {
mealPrice : "",
mealTax : 0.05,
tipPercent : 0.05
}
$scope.user = angular.copy(defaultForm);
$scope.cancel = function () {
$scope.myForm.$setPristine();
$scope.user = angular.copy(defaultForm);
console.log('empty');
}
答案 1 :(得分:3)
$scope.master = {};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
$scope.user = angular.copy($scope.master);
form.$setUntouched();
}
答案 2 :(得分:1)
如果ng-model
绑定到$scope.user.price
,$scope.user.tax
和$scope.user.tip
,这将有效。但是,它们必须$scope.price
,$scope.tax
和$scope.tip
。
设置表单$pristine
仅标记未被用户修改的值。它实际上并没有改变这些值。
解决方案A:
将模型绑定到user.*
并替换
$scope.mealPrice = '';
$scope.mealTax = 0.05;
$scope.tipPercent = 0.05;
与
$scope.user = {
mealPrice: '',
mealTax: 0.05,
tipPercent: 0.05
};
解决方案B:
替换:
$scope.user = angular.copy(defaultForm);
与
$scope.mealPrice = defaultFrom.mealPrice;
$scope.mealTax = defaultFrom.mealTax;
$scope.tipPercent = defaultFrom.tipPercent;