【发布时间】:2014-12-20 19:08:04
【问题描述】:
我只是尝试使用角度函数 $setPristine 和 $setUntouched 重置表单(使用 ng-repeat 创建了几个表单)。
我使用语法 {{ someName }} 动态分配表单名称(名称在服务器端构建,并作为 json(字符串)传递)。
表单的名称在标记中正确分配,并且验证按预期工作。当我将该名称作为参数传递给 ng-click="reset(someName)" 函数时,问题就出现了。
调试时,名称以字符串形式出现,而不是导致错误的表单对象。我通过对名称进行硬编码并通过相同的名称进行了快速测试,它工作正常。
我的假设是,来自 json 的名称是一个字符串,类型按原样转发给函数,而不是对象。
所以问题是:有没有办法转换该名称,以便控制器正确解释它。或者也许我还缺少其他东西......
这是标记(注意表单的名称使用 {{ resto.contactForm }}):
<form novalidate name="{{ resto.contactForm }}" ng-submit="submit(restoContact, resto.contactForm.$valid)" class="sky-form">
<div class="form-group">
<label class="checkbox state-success">
<input type="checkbox" ng-model="restoContact.sameAsUser" name="sameAsUser" id="sameAsUser" value="true" ng-click="contactAutoFill()"><i></i>Contact name is same as current user.
<input type="hidden" name="sameAsUser" value="false" />
</label>
</div>
<div class="form-group">
<label class="control-label" for="contactName">Contact Name</label>
<input type="text" ng-model="restoContact.contactName" name="contactName" id="contactName" placeholder="John, Doe" class="form-control" required />
<div ng-show="{{ resto.contactForm }}.contactName.$error.required && !{{ resto.contactForm }}.contactName.$pristine" class="note note-error">Please enter a name or check the box 'Same as current user'.</div>
</div>
<div class="form-group">
<label class="control-label" for="contactPhoneNumber">Contact Phone Number</label>
<input type="text" ng-model="restoContact.contactPhoneNumber" name="contactPhoneNumber" id="contactPhoneNumber" placeholder="+1 555-1234-567" class="form-control" required ng-pattern="phoneNumberPattern" />
<div ng-show="({{ resto.contactForm }}.contactPhoneNumber.$error.required || {{ resto.contactForm }}.contactPhoneNumber.$error.pattern) && !{{ resto.contactForm }}.contactPhoneNumber.$pristine" class="note note-error">Please enter a valid phone number.</div>
</div>
<div class="margin-leftM19">
<button class="btn btn-primary">Save Changes </button>
<button class="btn btn-default" ng-click="reset(resto.contactForm)">Cancel </button>
</div>
</form>
这是控制器中的重置功能(表单为“contactForm1”,这是正确的名称,但它是一个字符串而不是对象):
$scope.reset = function (form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
//$scope.user = angular.copy($scope.master);
};
我还没有实现提交方法,但我确信我会遇到同样的问题。 欢迎任何建议或意见。 提前谢谢...
这里是 fidle.js。变量数据是来自服务器的准确响应。
[http://jsfiddle.net/bouchepat/v0mtbxep/]
解决方案:
http://jsfiddle.net/bouchepat/v0mtbxep/3/
我删除了 $setUntouched,因为它会引发错误。
【问题讨论】:
-
你能为此创建一个 plnkr 或 fiddle 吗?
-
真的需要动态命名表单吗?最后,它有点武断,并没有真正直接与
ng-models 绑定
标签: angularjs