gpt4 book ai didi

javascript - AngularJS 指令模板 ng-repeat 有趣的替换

转载 作者:行者123 更新时间:2023-12-03 10:52:19 25 4
gpt4 key购买 nike

我正在努力处理 angularjs 指令模板。 {{variable}} 在 ng-repeat 中以一种非常奇怪的方式工作,

<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/ .

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

谢谢!

最佳答案

原因是您正在更新 same object reference 上的属性(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

关于javascript - AngularJS 指令模板 ng-repeat 有趣的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28389437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com