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>
                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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With