Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: radiobuttons stop firing "ng-change" after each one was clicked

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.

like image 759
graph Avatar asked Nov 18 '12 19:11

graph


1 Answers

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.

like image 167
Michelle Tilley Avatar answered Oct 13 '22 23:10

Michelle Tilley