且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS - 选择单选按钮时触发

更新时间:2022-02-03 22:21:04

在单选按钮选择上调用函数的方法至少有 2 种:

There are at least 2 different methods of invoking functions on radio button selection:

1) 使用 ng-change 指令:

<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>

然后,在控制器中:

$scope.newValue = function(value) {
     console.log(value);
}

这里是 jsFiddle:http://jsfiddle.net/ZPcSe/5/

Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/

2) 观察模型的变化.这不需要输入级别的任何特殊内容:

2) Watching the model for changes. This doesn't require anything special on the input level:

<input type="radio" ng-model="value" value="foo">

但在控制器中会有:

$scope.$watch('value', function(value) {
       console.log(value);
 });

还有 jsFiddle:http://jsfiddle.net/vDTRp/2/

And the jsFiddle: http://jsfiddle.net/vDTRp/2/

更多地了解您的用例将有助于提出适当的解决方案.

Knowing more about your the use case would help to propose an adequate solution.