AngularJs指令在变化时获得单选按钮ng-model值

时间:2014-12-04 09:52:43

标签: javascript angularjs angularjs-directive

我创建了一个循环遍历ng-repeat的Angular js指令,如果用户选择任何一个单选按钮,它应该提醒当前的ng-model值。

但它不起作用。请帮忙。



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);
      });
    }
  };
});
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

这很有效。

radioSelected 需要是对象的属性(例如, test )。这里给出了解释https://github.com/angular/angular.js/wiki/Understanding-Scopes

另外,我在手表中对 undefined 进行了测试,以避免加载时出现第一个警报。

&#13;
&#13;
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);
      });
    }
  };
});
&#13;
<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>
&#13;
&#13;
&#13;