2

I am having an ng-repeat block and with it i am writing an ng-click with a direct expression of setting a $scope variable to true.. but it doesn't work.. can someone plz help.. here is the plnkr

HTML:

selected: {{selected}}
    <ul>
      <li ng-repeat="t in t.header" ng-click="selected = true;">{{t.a1}}</li>
    </ul>

JS:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.selected = false;
  $scope.t = {
    header: [
      {
        a1:'a1'
      },
      {
        a1:'a1'
      }
    ]
  }
});

for now i am having a workaround to have a function call on its click and set the variable that is required, but curious to know whats wrong with the other approach?

1
  • there should be something like a $parent.selected, only selected doesn't make any sense Commented Apr 1, 2015 at 8:09

4 Answers 4

4

Use $parent because ng-repeat creates it's own scope

<li ng-repeat="t in t.header" ng-click="$parent.selected = true;">{{t.a1}}</li>

Plunker

Sign up to request clarification or add additional context in comments.

1 Comment

$parent did the trick, marking this as answer as it is close match to my prob.. other solutions provided works as well.. thanks everyone..
2

It's working, but because of the ngRepeat, selected is binded to the new scope. You can instead put selected in an object, so it won't create a new selected property on the child scope:

<li ng-repeat="t in t.header" ng-click="selectedObj.selected = true;">{{t.a1}}

$scope.selectedObj = { selected: false };

Check this plunker.

Comments

0

Try this:

//$scope.selected = false;
  $scope.model = {};
  $scope.model.selected = false;

plnkr

What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.

For better understanding: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Comments

0

Just use $parent scope, like this:

<li ng-repeat="t in t.header" ng-click="$parent.selected = true;">

Every item in ng-repat has his own scope.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.