Search code examples
angularjsangularjs-scope

ng-change is not working after one selection


I have already read this solution where @ryeballar gives the answer to the problem as that the scope of ng-repeat and controller are clashing so using either $parent/controller as syntax will solve the problem. But somehow in my case, the solution doesn't seem to work. The ng-change is not called at all, even after declaring it as a controller As. Also it is giving me weird output as well.
I have created a plunker for the same.

HTML

 <tr ng-repeat="item in renew.items">
     <td>{{item.deviceId}}</td>
     <td>{{item.carName}}</td>
     <td>{{item.regNumber}}</td>
     <td><input type="radio" name="{{item.deviceId}}" ng-model="renew.foo" ng-value="Monthly" ng-change="renew.updatePref(item, 'Monthly')">Monthly
     <input type="radio" ng-value="Yearly" ng-model="renew.bar" name="{{item.deviceId}}" ng-change="renew.updatePref(item, 'Yearly')">Yearly
     </td>
     <td>{{item.planStatus}}</td>
 </tr>

Here I have two radio buttons namely Monthly and Yearly created with the same name = item.deviceId so that only one remains clicked at a time. Firstly I have tried a lot of things. Setting ng-value to true so that Monthly is checked initially Which works but ng-change stops working and don't get called on a re-click. Can anybody guess why?The exact behaviour that I want is listed in the comments in Index.html.


Solution

  • Please change, initially

    vm.foo = 'Monthly'
    
    <input type="radio" name="{{item.deviceId}}" ng-model="renew.foo" ng-value="'Monthly'" ng-click="renew.updatePref(item, 'Monthly')">Monthly
    <input type="radio"  name="{{item.deviceId}}" ng-model="renew.bar" ng-value="'Yearly'" ng-click="renew.updatePref(item, 'Yearly')">Yearly
    

    you have use ng-change, change event never happen as value for these input remains always same. use,

    var vm = this;
    

    you are also using ng-value="Monthly", Monthly is variable (undefiend) for ng-value. either use value="Monthly" or ng-value="'Monthly'".

    Working Demo of Your Code