我创建了一个循环遍历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;
答案 0 :(得分:4)
这很有效。
radioSelected 需要是对象的属性(例如, test )。这里给出了解释https://github.com/angular/angular.js/wiki/Understanding-Scopes
另外,我在手表中对 undefined 进行了测试,以避免加载时出现第一个警报。
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;