Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

angularjs

I am new to AngularJS and have some trouble understanding the concept of scope in Angular. I have read some posts on stackoverflow as well as online articles, which advise me to create a custom directive to create an isolate scope, but I am getting nowhere...

As for the project I'm working on, I am trying to make a button that when clicked, will trigger a textarea. However, because of ng-repeat, the textarea is triggered for all buttons while I click only one.

My .js file:

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>
like image 321
root Avatar asked Jun 18 '15 03:06

root


2 Answers

Angular is creating child (NOT isolated) scope when ng-repeating, try this out, when you ng-init a variable, it is only visible within that 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

like image 174
rabbit.aaron Avatar answered Sep 30 '22 19:09

rabbit.aaron


There is no need to use a directive. You need to use object in the foreach to refer each item in the loop.

Add visible to each object in objectList:

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

Then the toggle button will need to pass the object to toggle:

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

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

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

Plunkr

like image 22
Wayne Ellery Avatar answered Sep 30 '22 19:09

Wayne Ellery