Skip to content Skip to sidebar Skip to footer

How To Stop Propagation When Using Ng-repeat (or How To Better Isolate Scope)

Noob question here I am trying to find the best way to set a scope variable inside of a ng-repeat. Since each index of the list will have the same scope variable, I am seeing chang

Solution 1:

Add expanded as a boolean to the item instead of to scope. Then use a private variable to keep the previous expanded item which can then be collapsed:

var expandedItem;

$scope.myFunct = function(item) {
    if (expandedItem && expandedItem != item) {
        expandedItem.expanded = false;
    }
    expandedItem = item;
    item.expanded = !item.expanded;
};
<divng-if="!item.expanded">{{item.shortTitle}}</div><png-if="item.expanded">{{item.longTitle}}</p>

Plunkr

Solution 2:

You could just do it via this.expanded = item, since this context will just be the child scope created by ng-repeat.

$scope.myFunct = function(item) {
 this.expanded = item;
};

If you want to be really explicit, then just pass in ng-click="myFunct(item, this)" and do:

$scope.myFunct = function(item, childScope) {
  childScope.expanded = item;
};

The reason behind passing this as ng-click argument is because every scope has a property called this which points to itself, and unlike passing this on events called via DOM, ng-click does not work that way, it evaluates arguments against the scope, so scope[this] ==> scope.

And ofcourse you could as well do:-

ng-click="expanded = item"

but it is better to isolate logic to your controller.

Post a Comment for "How To Stop Propagation When Using Ng-repeat (or How To Better Isolate Scope)"