0

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 Answers 2

5

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;
};
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Again, great Idea with the item parameter. Thank you very much for your speedy reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.