gpt4 book ai didi

javascript - AngularJs 指令在更改时获取单选按钮 ng-model 值

转载 作者:行者123 更新时间:2023-11-30 10:09:34 24 4
gpt4 key购买 nike

我创建了一个通过 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);
});
}
};
});
<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>

最佳答案

这有效。

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

此外,我在 watch 中测试了 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);
});
}
};
});
<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>

关于javascript - AngularJs 指令在更改时获取单选按钮 ng-model 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27290905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com