NewToJS
NewToJS

Reputation: 2101

AngularJS: Automatically select a radio button

I have two radio buttons and I want the first to be automatically selected

<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.

I have the first one to be selected in my controller but for some reason it's not working...

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

this.explicitDisabled = false;

this.playlistSelected = this.cleanPlaylist;

})

Upvotes: 0

Views: 1495

Answers (2)

developer033
developer033

Reputation: 24864

You must set a value for radio button, ng-value is an angular expression to which ng-model will be be set when the radio is selected, according to docs.

Then, to make it works you can do it as following:

(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>

Upvotes: 2

Adrian Brand
Adrian Brand

Reputation: 21628

playlistSelected is null, it will need a value that matches the value of the radio button. What is cleanPlaylist? Why not just hardcode the value of the radio and then set the playlistSelected to that value in the controller.

Upvotes: 0

Related Questions