AngularJS – select单选button时触发

我search并尝试了许多ng-xxxxtypes的选项,但找不到一个..我只是想调用控制器中的一些function,当单选button被选中。

所以它可能类似于以下..(当然,下面的代码不工作)

<input type="radio" ng-model="value" value="one" ng-click="checkStuff()"/> 

有什么办法实现我想要的?

在单选buttonselect上至less有两种不同的调用函数的方法:

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/

2)观察模型的变化。 这在input级别上不需要特别的东西:

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

但是在一个控制器中会有:

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

和jsFiddle: http : //jsfiddle.net/vDTRp/2/

了解更多关于你的用例将有助于提出一个适当的解决scheme。

如果触发源不是点击,应该使用ngChange而不是ngClick。

下面是你想要的? 你的情况究竟怎么样?

 var myApp = angular.module('myApp', []); function MyCtrl($scope) { $scope.value = "none" ; $scope.isChecked = false; $scope.checkStuff = function () { $scope.isChecked = !$scope.isChecked; } } <div ng-controller="MyCtrl"> <input type="radio" ng-model="value" value="one" ng-change="checkStuff()" /> <span> {{value}} isCheck:{{isChecked}} </span> </div> 

在更新版本的angular(我使用1.3),你可以基本上设置模型和价值和双重绑定做这个例子工作的所有工作就像一个魅力:

 angular.module('radioExample', []).controller('ExampleController', ['$scope', function($scope) { $scope.color = { name: 'blue' }; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <html> <body ng-app="radioExample"> <form name="myForm" ng-controller="ExampleController"> <input type="radio" ng-model="color.name" value="red"> Red <br/> <input type="radio" ng-model="color.name" value="green"> Green <br/> <input type="radio" ng-model="color.name" value="blue"> Blue <br/> <tt>color = {{color.name}}</tt><br/> </form> </body> </html> 

对于dynamic值!

 <div class="col-md-4" ng-repeat="(k, v) in tiposAcesso"> <label class="control-label"> <input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" /> <span ng-bind="v"></span> </label> </div> 

在控制器中

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

我更喜欢使用ng-value和ng-if,[ng-value]来处理触发器的变化

 <input type="radio" name="isStudent" ng-model="isStudent" ng-value="true" /> //to show and hide input by removing it from the DOM, that's make me secure from malicious data <input type="text" ng-if="isStudent" name="textForStudent" ng-model="job"> 

另一种方法是使用Object.definePropertyvalue设置为控制器作用域中的getter setter属性,然后value属性的每次更改都会触发setter中指定的函数:

HTML文件:

 <input type="radio" ng-model="value" value="one"/> <input type="radio" ng-model="value" value="two"/> <input type="radio" ng-model="value" value="three"/> 

JavaScript文件:

 var _value = null; Object.defineProperty($scope, 'value', { get: function () { return _value; }, set: function (value) { _value = value; someFunction(); } }); 

看到这个笨蛋的执行情况