sergioFC
sergioFC

Reputation: 6016

Angularjs only triggering ng-change on input radio the first time its selected

I have made a simple example using angularjs. This example contains three radio inputs, each of which have to call a function on change (ng-change => console.log). Unfortunately, the function its only triggered the first time any radio input is selected.

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

Upvotes: 3

Views: 5270

Answers (2)

PSL
PSL

Reputation: 123739

Couple of issues/changes:-

1- Change value={{value}} to ng-value="value" because ng-value - Binds the given expression to the value of input[select] or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.

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

3- You do not need to pass the model value though logChange scope will already have it.

Try:-

In your controller add:-

  $scope.selected = {};

and view set the model as a property on selected property of controller scope instead of ng-repeated child scope's val property:-

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

Plnkr

Upvotes: 6

ohboy21
ohboy21

Reputation: 4319

You can change ng-change to ng-click, then it fires every time you actually click on the button.

Here is a JSFiddle.

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

If you bind ng-model to "values" or whatever, you can check which value it has and work with that. Angulars advantage is exactly this two-way-databinding without doing anything. No need to call a function to pass an argument.

Upvotes: 3

Related Questions