15

I am building radio buttons dynamically. ng-change='newValue(value) stops being called after each radio button has been pressed once.

this works: Clicking on the radio buttons changes the value to foo/bar/baz. http://jsfiddle.net/ZPcSe/19/

<div ng-controller="MyCtrl">
<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>
<input type="radio" ng-model="value" value="bar" ng-change='newValue(value)'>
<input type="radio" ng-model="value" value="baz" ng-change='newValue(value)'>    
<hr>
{{value}}
</div>

this code does not: The {{value}} - "label" is not updated once each radio button has been pressed at least once. Aparently ng-change is not fired any more.

<div ng-controller="MyCtrl">
    <span ng-repeat="i in [0, 1, 2]">
    <input name="asdf" type="radio" ng-model="value" value={{i}} ng-change='newValue(value)'>   
    </span>
    {{value}}
</div>

http://jsfiddle.net/ZPcSe/18/

The Controlles is the same each time:

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

function MyCtrl($scope) {
    $scope.value = '-';
    $scope.newValue = function(value) {
    $scope.value = value;
    }
}

Thanks for your help.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
graph
  • 367
  • 1
  • 6
  • 18

3 Answers3

22

ngRepeat creates new scope, so trying to set value sets it on the new scope. The workaround is to reference a property on an object that is on the parent scope--the object lookup happens on the parent scope, and then changing the property works as expected:

HTML:

<div ng-controller="MyCtrl">
<span ng-repeat="i in [0, 1, 2]">
  <input name="asdf" ng-model="options.value" value="{{i}}" type="radio">
</span>
{{options.value}}

JS:

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

function MyCtrl($scope) {
    $scope.options = {
        value: '-'
    };
    $scope.newValue = function(value) {
        // $scope.options.value = value; // not needed, unless you want to do more work on a change
    }
}​

You can check out a working fiddle of this workaround. See angular/angular.js#1100 on GitHub for more information.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • 1
    This seems like magic - how and where is `$scope.newValue` called? There is no `ng-change` event specified in the HTML, so where does it fire? – Richard Nov 13 '13 at 15:37
  • @Richard It doesn't fire; it was a function in the original question, so I copied it over; I think the `console.log` was left in from some debugging on JSFiddle. – Michelle Tilley Nov 13 '13 at 17:08
4

Just a quick work-around, we can achieve the same- using ng-model="$parent.value", because it would refer to the parent of ng-repeat scope i.e- in myCtrl scope

Only Change in ng-model-

<input name="asdf" type="radio" ng-model="$parent.value" value={{i}} ng-change='newValue(value)'>

Here is the fiddle

Avisek Chakraborty
  • 8,229
  • 10
  • 48
  • 76
-1

Try ng-click instead of ng-change.

xlm
  • 6,854
  • 14
  • 53
  • 55
Deep Shah
  • 198
  • 2
  • 5