0

I'm trying to create a button based filter, but as soon as I attach the filter to ng-repeat it does not work anymore (NOTE, the objects that need to be filtered are in another ng-repeat).

<!-- This works -->
<div ng-click="myFilter = {name: 'Test'}">button</div>

<!-- This does not work -->
<span ng-repeat="(key, button) in gl_categories">
    <div ng-click="myFilter = {name: 'Test'}">{{button}}</div>
</span>
yodalr
  • 9,778
  • 10
  • 32
  • 47

2 Answers2

1

AngularJS developers recommend do not write code on the templates. The templates must be used like read only.

In your case, the problem is because the ng-repeat create a new scope for each iteration. You are writing on the iteration scope.

Try to use a function instead of the manual assigment.

$scope.setFilter = function(value){
  $scope.myFilter = {name: value}
}

later

<span ng-repeat="(key, button) in gl_categories">
    <div ng-click="setFilter('test')">{{button}}</div>
</span>
chfumero
  • 1,137
  • 2
  • 13
  • 26
0

Because ngRepeat creates its own child scope, and each time that click event happens, another myFilter variable gets created on that scope. You can use an object, then set the object property (this will bubble up)

<div ng-click="x.myFilter = {name: 'Test'}">button</div>

<span ng-repeat="(key, button) in gl_categories">
    <div ng-click="x.myFilter = {name: 'Test'}">{{button}}</div>
</span>

I'd recommend reading the following post for an awesome explanation: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Community
  • 1
  • 1
tymeJV
  • 103,943
  • 14
  • 161
  • 157