我使用路由将不同的模板加载到 ngView 中。其中一个模板有一个简单的 Controller ,其中包含一组触点。我在这里尝试做的事情很简单,只需单击链接 (ngclick) 调用函数并将新对象添加到数组中,我希望该对象将反射(reflect)在我的 UI 中。
是这样的:
$scope.contacts = [{name='', email=''}];
<li ng-repeat="con in contacts">
<input type="text" ng-model="con.name"/>
<input type="email" ng-model="con.email"/>
</li>
<li>
<a href ng-click="addContact()">add</a>
</li>
$scope.addContact = function() {
$scope.contacts.push( {name='', email=''} ); //-- i can use either $scope or this to reference the array and works.
}
因此,UI 使用初始值呈现良好,单击时调用 addContact 函数,我看到该值被推送(长度 = 2),但随后该函数结束数组似乎被重置为一个元素(长度 = 1)在AngularJS评估之后。
我不确定是否会发生这种情况,因为我使用 ngView。我的意思是,我回顾了这个示例(http://code.angularjs.org/1.0.3/docs/api/ng.directive:ngController),我没有看到我在这里尝试做的事情有多大差异,不同之处在于我将路由与 ngView 一起使用。
fiddle :http://jsfiddle.net/fdDph/
非常感谢您的帮助。
最佳答案
在 Fiddle 中,您将 ng-show 中的数组长度重置为 1:
<span ng-hide="contacts.length = 1">
这样做就会起作用:
<span ng-hide="contacts.length == 1">
关于angularjs - 在 ngView 中动态添加新的表单字段 - Angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13916694/