javascript AngularJS:动态添加元素到 <li>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20121656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: Add Elements to <li> dynamically
提问by rohitpal
I am unable to populate list on clicking Add button. Problem is when I change the text field again, My List data gets changed (binding), how to avoid that?
我无法在单击“添加”按钮时填充列表。问题是当我再次更改文本字段时,我的列表数据被更改(绑定),如何避免?
HTML
HTML
<div class="control-group">
<label class="control-label" for="projectManager">Project Manager(s)</label>
<div class="row controls" >
<input type="text" class="span3" placeholder="Manager name" ng-model="pm.name">
<input type="text" class="span2" placeholder="Manager type" ng-model="pm.type">
<button type="button" ng-click="addManagersForm()"> Add </button>
</div>
<div class="row controls" >
<ul><li ng-repeat="tPm in pms">{{tPm.name}}</li></ul>
</div>
</div>
JS
JS
app.controller('myContrl',["$scope", "$http", function($scope, $http) {
$scope.pms = [];
$scope.addManagersForm = function() {
console.log($scope.pm);
$scope.pms.push($scope.pm);
};
}]);
采纳答案by Beterraba
It happens because you are pushing the $scope.pm
object into the array, and that object is binded in the form.
发生这种情况是因为您将$scope.pm
对象推入数组,而该对象已绑定在表单中。
Just create a new object and you will be fine:
只需创建一个新对象就可以了:
$scope.addManagersForm = function() {
var pm = $scope.pm;
$scope.pm = {}; // Do this to clean up the form fields
$scope.pms.push(pm);
};
回答by David Riccitelli
It's because instances are passed by reference. You can use angular.copyto create a deep copy of it.
这是因为实例是通过引用传递的。您可以使用angular.copy来创建它的深层副本。
See this example Plunker: http://plnkr.co/edit/d8HwXzTBK61sMuwLollW
请参阅此示例 Plunker:http://plnkr.co/edit/d8HwXzTBK61sMuwLollW
The updated code:
更新后的代码:
HTML page
HTML页面
<body ng-app="app" ng-controller="myContrl">
<div class="control-group">
<label class="control-label" for="projectManager">Project Manager(s)</label>
<div class="row controls" >
<input type="text" class="span3" placeholder="Manager name" ng-model="pm.name">
<input type="text" class="span2" placeholder="Manager type" ng-model="pm.type">
<button type="button" ng-click="addManagersForm(pm)"> Add </button>
</div>
<div class="row controls" >
<ul><li ng-repeat="tPm in pms">{{tPm.name}}</li></ul>
</div>
</div>
JavaScript
JavaScript
angular.module('app', []).controller('myContrl',["$scope", "$http", function($scope, $http) {
$scope.pms = [];
$scope.addManagersForm = function(pm) {
console.log(pm);
$scope.pms.push(angular.copy(pm));
};
}]);