2015-02-08 77 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