Behavior of assignment expression invoked by ng-click within ng-repeat

kdgregory picture kdgregory · Mar 13, 2013 · Viewed 32.3k times · Source

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).

Answer

Stewie picture Stewie · Mar 13, 2013

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.