angular mulitiple ng-hide using same variable

79 views Asked by At

I'm stuck with something, that should be quite ordinary. I'm about to write a factory to solve this problem, but was thinking, that there must be a clever way out of this.

I have a ng-repeat in my directive templateUrl:

<div ng-repeat="item in items">
   <p ng-click="toggle()" ng-hide="display">{{item.$value}}</p>
   <input ng-model="item.$value" ng-show="display">
   <button ng-show="display" ng-click="changeText(item)">finish</button>
</div>

My toggle function looks like this:

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

That means, when I click on one <p> element, all input-fields are being displayed. Since they all are using the same variable. I can't wrap my head around making a proper angular solution to this problem, so that only the one within this item is being toggled. Does such a solution even exist?

2

There are 2 answers

0
Zee On

One simple way to make it is to use item.display instead of display and pass item in toggle(). Something like this:

<div ng-repeat="item in items">
    <p ng-click="toggle(item)" ng-hide="item.display">{{item.$value}}</p>
    <input ng-model="item.$value" ng-show="item.display">
    <button ng-show="item.display" ng-click="changeText(item)">finish</button>
</div>

JS:

$scope.toggle = function (item) {
    item.display = !item.display;
};
1
Ziga Petek On

Try this:

<div ng-repeat="item in items">
     <p ng-click="toggle(item)" ng-hide="item.display">{{item.$value}}</p>
     <input ng-model="item.$value" ng-show="item.display">
     <button ng-show="item.display" ng-click="changeText(item)">finish</button>
</div>

$scope.toggle = function (item){
  item.display = item.display || false;
  item.display = !item.display;
}; 

If you keep the "display" flag inside the item, you can toggle it for each one individually. If "item.display" is not defined, it will be treated as "false".

At least that's how I usually do it, there may be better solutions though.