AngularJS:将元素添加到<li>动态</li>

时间:2013-11-21 12:58:04

标签: javascript jquery angularjs

单击“添加”按钮后,我无法填充列表。问题是当我再次更改文本字段时,我的列表数据被更改(绑定),如何避免?

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()">&nbsp;&nbsp;Add&nbsp;&nbsp;</button>
    </div>
    <div class="row controls" >
        <ul><li ng-repeat="tPm in pms">{{tPm.name}}</li></ul>
    </div>
</div>

JS

app.controller('myContrl',["$scope", "$http", function($scope, $http) {
    $scope.pms = [];

    $scope.addManagersForm = function() {
        console.log($scope.pm);
        $scope.pms.push($scope.pm);
    };

}]);

2 个答案:

答案 0 :(得分:2)

这是因为您正在将$scope.pm对象推入数组中,并且该对象在表单中绑定。

只需创建一个新对象就可以了:

$scope.addManagersForm = function() {
    var pm = $scope.pm;
    $scope.pm = {}; // Do this to clean up the form fields
    $scope.pms.push(pm);
};

答案 1 :(得分:1)

这是因为实例是通过引用传递的。您可以使用angular.copy创建它的深层副本。

请参阅此示例Plunker:http://plnkr.co/edit/d8HwXzTBK61sMuwLollW

更新的代码:

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)">&nbsp;&nbsp;Add&nbsp;&nbsp;</button>
    </div>
    <div class="row controls" >
        <ul><li ng-repeat="tPm in pms">{{tPm.name}}</li></ul>
    </div>
</div>

<强>的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));
    };

}]);