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/
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.