How to create a separate area isolated from ng-repeat in Angular?

I am new to AngularJS and have some problems understanding the scope concept in Angular. I read some stackoverflow posts, as well as articles on the Internet that advise me to create a custom directive to create an isolation area, but I can't go anywhere ...

As for the project I'm working on, I'm trying to make a button that, when clicked, will launch a text box. However, due to ng-repeat, the text field is triggered for all buttons while I click only one.

My .js file is:

angular.module('myApp') .controller('myCtrl', function ($scope, Question) { scope.visible = false; scope.toggle = function() { scope.visible = !scope.visible; }; .directive("myDirective", function () { return { scope: { ngClick: '&', ngShow: '&' } } }); 

Here is my HTML file:

 <ul> <li ng-repeat="object in objectList"> <button type="text" myDirective ng-click="toggle()">Click</button> <textarea myDirective ng-show="visible"></textarea> </li> </ul> 
+6
source share
2 answers

Angular creates a child (NOT isolated) area when ng-repeating, try this when you have an ng-init variable, it is visible only inside this repeat div.

 <div ng-repeat="i in [0,1,2,3,4,5,6,7,8,9]" ng-init="visible=false"> <button ng-click="visible=!visible">Toggle</button> <h1 ng-show="visible">look at me!</h1> </div> 

Plunker

+3
source

No need to use directive. You must use object in foreach to reference each element of the loop.

Add visible for each object in objectList :

 $scope.objectList = [ { visible: false }, { visible: false }, { visible: false } ]; 

Then, the switch button must be passed the object to switch:

 $scope.toggle = function (object) { object.visible = !object.visible; }; 

ng-show will need to check object.visible and ng-click need to pass an object:

 <button type="text" ng-click="toggle(object)">Click</button> <textarea ng-show="object.visible"></textarea> 

Plunkr

+3
source

Source: https://habr.com/ru/post/989315/


All Articles