Angularjs only trigger ng change on input radio on first select

I made a simple example using angularjs. This example contains three radio inputs, each of which must call a function on change (ng-change => console.log). Unfortunately, its function only worked at the first choice of the radio input.

HTML:

<div ng-app="myApp" ng-controller="radioGroupController">
    <div ng-repeat="value in values">{{value}}
        <input type="radio" name="name" ng-model="val" value="{{value}}" ng-change="logChange(val)" />
        <hr/>
    </div>
</div>

      

JS:

angular.module('myApp', [])
    .controller('radioGroupController', ['$scope', function ($scope) {
    $scope.values = ['Option1', 'Option2', 'Option3'];
    $scope.logChange = function (newValue) {
        console.log('Changed to ' + newValue);
    };
}]);

      

Am I doing something wrong or is this the expected beheaviour?

EDIT: fiddle

+3


source to share


2 answers


A couple of problems / changes: -

1- Change value={{value}}

to ng-value="value"

because ng-value - binds the given expression to the value of an input [select] or input [radio] so that when an element is selected, the ngModel of that element is set to the border value.

2- You need to set the selected property value in the parent area, you have ng-repeat and you actually set the value of the child area, so each radio has its own child area and its value never changes, so ng -change is not triggered ...

3- You don't need to pass the value to the model, although the scope logChange

already has it.

Try: -



In your controller add: -

  $scope.selected = {};

      

and the view sets the model as a property on a property selected

for the controller scope instead of the ng-repeat child scope val

property: -

 <input type="radio" name="name" ng-model="selected.val"
                  ng-value="value" ng-change="logChange()" />

      

Plnkr

+6


source


You can change ng-change

to ng-click

, then it fires every time you press the button.

Here's a JSFiddle .



Depending on what you want to achieve, consider $ watch or ng models for your purpose.

If you bind ng model to "values" or whatever you can check its value and work with that. The advantage of corners is exactly this two-way snapping without any action. You don't need to call to pass an argument.

+3


source







All Articles