I'm attempting to update my model using ng-click attached to a <p>.
I have no problem with an assignment expression outside of an ng-repeat, or with calling a scope method inside the ng-repeat. However, if I use an assignment inside the ng-repeat, it appears to be ignored. I don't see any messages reported in the Firefox console, but haven't tried setting breakpoints to see if the event is being fired.
<!DOCTYPE html>
<html>
<head>
<title>Test of ng-click</title>
<script type='text/javascript' src='http://code.angularjs.org/1.1.1/angular.js'></script>
<script type='text/javascript'>//<![CDATA[
function MyCtrl($scope) {
$scope.selected = "";
$scope.defaultValue = "test";
$scope.values = ["foo", "bar", "baz"];
$scope.doSelect = function(val) {
$scope.selected = val;
}
}
//]]>
</script>
</head>
<body ng-app>
<div ng-controller='MyCtrl'>
<p>Selected = {{selected}}</p>
<hr/>
<p ng-click='selected = defaultValue'>Click me</p>
<hr/>
<p ng-repeat='value in values' ng-click='selected = value'>{{value}}</p>
<hr/>
<p ng-repeat='value in values' ng-click='doSelect(value)'>{{value}}</p>
</div>
</body>
</html>
Fiddle is here, if you prefer (along with a couple of earlier variants).
Directive ngRepeat creates a new scope for each iteration, so you need to reference your variables in parent scope.
Use $parent.selected = value, as in:
<p ng-repeat='value in values' ng-click='$parent.selected = value'>{{value}}</p>
Note: Function call propagates due to prototypal inheritance.
If you want to learn more: The Nuances of Scope Prototypal Inheritance.
As @Stewie mentioned, $parent is one way to solve this issue. However, the recommended (by the Angular team) solution is to not define primitive properties on the $scope. Rather, the $scope should reference your model. Using references also avoids the issue (because primitive properties will not be created on the child scopes which hide/shadow the parent scope properties of the same name), and you don't have to remember when to use $parent:
HTML:
<p>Selected = {{model.selected}}</p>
<hr/>
<p ng-click='model.selected = defaultValue'>Click me</p>
<hr/>
<p ng-repeat='value in values' ng-click='model.selected = value'>{{value}}</p>
<hr/>
<p ng-repeat='value in values' ng-click='doSelect(value)'>{{value}}</p>
JavaScript:
$scope.model = { selected: ""};
...
$scope.doSelect = function (val) {
$scope.model.selected = val;
}
I recently updated the wiki page that @Stewie mentioned to always recommend this approach.