Digamos que tengo algo de código:
<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>Ahora, digamos que quiero hacer que cada "cosa" en la matriz "cosas" tenga su propio botón correspondiente. Cuando hago clic en el botón que corresponde a una "cosa" en particular, se mostrarán las entradas en la matriz de "partes" (una propiedad de una "cosa") y el texto "haz clic en mí" cambiará a "he hecho clic". Cuando vuelva a hacer clic en el botón, las entradas de la matriz de partes para esa "cosa" no se mostrarán, y el texto del botón volverá a decir "haga clic en mí".
¿Cómo exactamente haría esto? No estoy muy seguro de cómo manipular exactamente los elementos individuales dentro de una repetición ng.
Necesita un lugar para almacenar si una "cosa" está activa o no. Puede agregar una propiedad isActive en una thing o agregar una propiedad activeThing en su máquina virtual.
Para este ejemplo, póngalo en su VM.
Luego coloque un div con un ng-if dentro de su ng-repeat externo, así:
<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>Puede rastrear por id o rastrear por índice.
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>