AngularJS指令模板ng重复有趣的替换

AngularJS directive templates ng-repeat funny substitution

本文关键字:替换 指令 ng AngularJS      更新时间:2023-09-26

我很难使用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/.

我错过了什么或做错了什么?

谢谢!

原因是您每次都在更新同一对象引用(newItem)上的属性。所以它会更新数组中的所有其他项,因为它们都指向同一个对象,或者换句话说,它们都是相同的。相反,您可以使用angular.copy获取对象的副本,然后推送该项目。

    var item = {
        itemNum: 0,
        name: "New"
    };
    $scope.addItem = function () {
        var newItem = angular.copy(item); //Get the copy
        newItem.itemNum = $scope.count;

Fiddle