2015-02-08 75 views
0

我正在与angularjs指令模板挣扎。该{{变量}}工作在NG-重复里面一个很奇怪的方式,AngularJS指令模板ng重复有趣的替换

<div ng-controller="MyCtrl"> 
    <h2>here i am</h2> 
    <button type="button" ng-click="addItem()" class="btn btn-primary">Howdy</button> 
    <div ng-repeat="item in items track by $index" itemlist></div> 
</div> 

<script type="text/ng-template" id="template.html"> 
    <div> 
     Howdy {{item.itemNum}} {{item.name}} 
    </div> 
</script> 

var myApp = angular.module('myApp', []); 

myApp.controller('MyCtrl', function ($scope) { 
    $scope.count = 0; 

    $scope.items = []; 

    var newItem = { 
     itemNum: 0, 
     name: "New" 
    }; 

    $scope.addItem = function() { 
     newItem.itemNum = $scope.count; 
     console.log('adding item ' + newItem.itemNum); 
     $scope.items.push(newItem); 
     $scope.count += 1; 
    }; 
}); 

myApp.directive('itemlist', function ($compile) { 
    return { 
     templateUrl: 'template.html', 
    }; 
}); 

我已经创建出我的问题,这里的jsfiddle:http://jsfiddle.net/dk253/8jm5tjvf/23/

我缺少什么或者做错了吗?

谢谢!

回答

1

原因是你每次都更新same object referencenewItem)的属性。所以它更新数组中的所有其他项目,因为它们都指向相同的对象,换句话说它们都是相同的。您可以使用angular.copy获取对象的副本并推送该项目。

var item = { 
     itemNum: 0, 
     name: "New" 
    }; 

    $scope.addItem = function() { 
     var newItem = angular.copy(item); //Get the copy 
     newItem.itemNum = $scope.count; 

Fiddle

+0

@DaveKearney欢迎您。 – PSL 2015-02-08 01:38:29