Daniel Ortiz
Daniel Ortiz

Reputation: 921

how to make ng-click from within a ng-repeat affect outer scope

I am on the following situation, I have an element which adds a class through ng-click in other elements. Some of then are within a ng-repeat loop with its own scope... Something like that: <section id="sign-up" class="sign-up" ng-init="signUp = false"ng-class="{'active': signUp}">

and the elements that trigger the class change on click uses this ng-click="signUp = !signUp"

It works in any element that isn't inside the ng-repeat.. How can I make it work?

Upvotes: 0

Views: 89

Answers (1)

GregL
GregL

Reputation: 38103

This is a classic case of not following what I consider to be the AngularJS Golden Rule:

Whenever you want to set a property on the scope, either via ng-model or inside an expression, always make sure you have a . (dot/period) in the expression.

Because what is happening in your case is that the ng-repeat is creating a new scope for every item in the array. When you then have ng-click="signUp = !signUp", this creates a brand new signUp property on the scope for that item, rather than modifying the signUp property on the scope further up (via the prototype of the scope object). This is because whenever you set a property on a JS object, it sets it on the current object, even if the property is present on the prototype.

Instead, try changing it to use an intermediate object on the top level scope to hold the signUp property, so you refer to it as flags.signUp for example. This means that Angular looks up the value of flags first in the child scope, and finds the object on the parent scope via the prototype. Then it can set the signUp flag on the correct object, rather than on the child scope.

Does that all make sense?

Upvotes: 2

Related Questions