简体   繁体   中英

AngularJs Directive get radio button ng-model value on change

I have created an Angular js Directive that loops through ng-repeat and if users chooses any of those radio button, it should alert the current ng-model value.

But its not working. Please help.

 var someapp = angular.module('someapp', []); someapp.controller('someappCtrl', function($scope, $http) { //... }).directive('checkthemChoice', function() { return { restrict: 'A', template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>', link: function(scope, element, attrs) { scope.choices = ['organization', 'user']; element.on('change', function() { //this selected the parent DIV checkthem //but I want select the radio input inside LABEL }); scope.$watch('radioSelected', function(val) { //this doesnt work alert(val); }); } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="someapp" ng-controller="someappCtrl"> <div class="checkthem" checkthem-Choice=""></div> </div> 

This works.

radioSelected needs to be a property of an object (for example, test ). The explanation is given here https://github.com/angular/angular.js/wiki/Understanding-Scopes

Also, I have a put a test for undefined in the watch to avoid the first alert on load.

 var someapp = angular.module('someapp', []); someapp.controller('someappCtrl', function($scope, $http) { //... }).directive('checkthemChoice', function() { return { restrict: 'A', template: '<label ng-repeat="choice in choices" for="{{ choice }}"><input type="radio" ng-checked="$first" name="selecttable" ng-model="test.radioSelected" value="{{ choice }}" id="{{ choice }}"> {{ choice }}</label>', link: function(scope, element, attrs) { scope.choices = ['organization', 'user']; scope.test = {}; element.on('change', function() { //this selected the parent DIV checkthem //but I want select the radio input inside LABEL }); scope.$watch('test.radioSelected', function(val) { if (val !== undefined) alert(val); }); } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="someapp" ng-controller="someappCtrl"> <div class="checkthem" checkthem-Choice=""></div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM