AngularJS:自动选择一个单选按钮

时间:2016-07-07 22:48:49

标签: javascript angularjs radio-button

我有两个单选按钮,我希望第一个被自动选择

<input type="radio" name="playlist" ng-value="myCtrl.cleanPlaylist" ng-model="myCtrl.playlistSelected"> Clean

<input type="radio" name="playlist" ng-value="myCtrl.explicitPlaylist" ng-model="myCtrl.playlistSelected" ng-disabled="myCtrl.

我有第一个在我的控制器中被选中但由于某种原因它不起作用......

var myModule = angular.module("MyApp", []).controller('MyController', function(){

this.explicitDisabled = false;

this.playlistSelected = this.cleanPlaylist;

})

2 个答案:

答案 0 :(得分:2)

您必须为单选按钮设置一个值,ng-value是一个角度表达式,当选择了收音机时,ng-model将被设置,根据 docs

然后,为了使其有效,您可以按照以下方式执行:

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function() {
      var vm = this;
      
      vm.playlistSelected = 'clean';
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl as main">
  <input type="radio" name="playlist" value="clean" ng-model="main.playlistSelected"> Clean
  <input type="radio" name="playlist" value="complete" ng-model="main.playlistSelected"> Complete
</body>

</html>

答案 1 :(得分:0)

playlistSelected为null,它需要一个与单选按钮值匹配的值。什么是cleanPlaylist?为什么不硬编码无线电的值,然后将playlistSelected设置为控制器中的该值。