FishBulbX FishBulbX -4 years ago 56
AngularJS Question

AngularJS - ng-click in an ng-repeat not executing

In the following code, ng-click does not assign 'color' to 'selected_color'... why is that?

<div ng-app>
<div ng-controller="xCtrl">
<div ng-repeat="color in colors" ng-click="selected_color=color" style="cursor:pointer;">{{ $index }} - {{ color }}</div>
<hr>
Selected Color: {{ selected_color }}
</div>
</div>


Example: http://jsfiddle.net/s6vrz184/

Answer Source

It does, just not how you think. ngRepeat creates its own child scope, so in essence, each time you click, you're creating a new variable called selected_color on that child scope and setting it.

Create a method on your controller and call that instead:

$scope.setColor = function(color) {
    $scope.selected_color = color;
}

And use this:

<div ng-repeat="color in colors" ng-click="setColor(color)" style="cursor:pointer;">{{ $index }} - {{ color }}</div>

Updated fiddle: http://jsfiddle.net/s6vrz184/1/

If you're opposed to using a controller function for some reason, you can $parent to set the selected_color variable inline, altho this isn't recommended:

<div ng-repeat="color in colors" ng-click="$parent.selected_color=color" style="cursor:pointer;">{{ $index }} - {{ color }}</div>

$parent fiddle: http://jsfiddle.net/s6vrz184/2/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download