假設我有一些代碼:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="hey">
<div class="dude" ng-repeat="thing in things">
<button type="button" ng-click="doStuff()">click me</button>
<div ng-repeat="p in {{thing.parts}}">Part {{$index}}: {{p}}</div>
</div>
</div>
</div>
現在,假設我想讓“事物”陣列中的每個“事物”都有自己對應的按鈕。當我單擊與一個特定“事物”對應的按鈕時,將顯示“零件”陣列(“事物”的屬性)中的條目,并且文本“單擊我”將更改為“已單擊”。當您再次單擊該按鈕時,將不會顯示該“事物”的部件陣列條目,并且該按鈕的文本將回傳說“單擊我”。
我將如何做到這一點?我不太確定如何在 ng-repeat 中操作單個元素。
uj5u.com熱心網友回復:
如果“事物”處于活動狀態,您需要在某個地方存盤。您可以在 VMisActive上添加屬性thing或activeThing在 VM上添加屬性。
對于此示例,請將其放在您的 VM 上。
然后,把div與ng-if你的外內ng-repeat,像這樣:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="hey">
<div class="dude" ng-repeat="thing in things">
<div ng-if="thing !== activeThing">
<button type="button" ng-click="activeThing = thing">click me</button>
</div>
<div ng-if="thing === activeThing">
<button type="button" ng-click="activeThing = undefined">Clicked</button>
<div ng-repeat="p in {{thing.parts}}">Part {{$index}}: {{p}}</div>
</div>
</div>
</div>
</div>
uj5u.com熱心網友回復:
您可以按 id 或按索引跟蹤。
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.things = [{
id: 1,
title: "Thing Foo",
parts: ["a", "b", "c"]
},
{
id: 2,
title: "Thing Bar",
parts: ["d", "e", "f"]
}
];
$scope.doStuff = function(id, index) {
let thing
if (id) thing = $scope.things.find(t => t.id === id)
else thing = $scope.things[ index]
console.log(`${thing.title} clicked`);
thing.show = !thing.show;
if (!thing.show) return;
let c = thing.numClicks ? thing.numClicks 1 : 1;
thing.numClicks = c;
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="hey">
<div class="dude" ng-repeat="thing in things">
<button type="button" ng-click="doStuff(thing.id)">click me (id)</button>
<button type="button" ng-click="doStuff(false, $index)">click me (index)</button>
<div ng-show="thing.show">
<h3>Clicked {{thing.numClicks}} times</h3>
<div ng-repeat="p in thing.parts">Part {{$index}}: {{p}}</div>
</div>
<hr>
</div>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389060.html
上一篇:如何對地圖中的特定值進行排序
