一次选择后,ng-change无效

时间:2016-10-06 21:23:58

标签: angularjs angularjs-scope

我已经阅读了this解决方案,其中@ryeballar给出了问题的答案,因为ng-repeat和控制器的范围发生了冲突,因此使用$parent/controller as语法将解决问题。但不管怎样,在我的情况下,解决方案似乎并不奏效。即使在将其声明为控制器As之后,也根本不会调用ng-change。它也给了我奇怪的输出。
我为此创建了plunker

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>

这里我有两个单选按钮,即每月和每年使用相同的name = item.deviceId创建,这样一次只能点击一个。 首先,我尝试过很多东西。将ng-value设置为true,以便最初检查每月哪个有效,但ng-change停止工作,并且不会在重新点击时调用。任何人都可以猜到为什么?我想要的确切行为列在Index.html的评论中。

2 个答案:

答案 0 :(得分:1)

请改变, 最初

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

您使用了ng-change,因为这些输入的值始终相同,所以更改事件永远不会发生。 使用中,

var vm = this;

您还使用ng-value="Monthly",每月{ng}值为variable (undefiend)。使用value="Monthly" or ng-value="'Monthly'".

Working Demo of Your Code

答案 1 :(得分:0)

当您使用controllerAs时,您的主要问题是将内容分配给$ scope

当您将这些功能作为控制器的属性时,它们可以正常工作

clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f460d8929d0)

然后将$ scope的所有引用更改为 app.controller('testCntrl', ['$scope', '$uibModal', function($scope, $uibModal) { var vm = this;// store reference ALWAYS!

vm

Generally working demo (not all scope conversions done)