如何在Angularjs中将选定的无线电传递给控制器

时间:2015-09-23 19:36:44

标签: javascript angularjs

请告诉我如何console.log()所选电台?我还尝试通过添加checked="checked"来选择默认值,但ID无效

<body ng-app="app">
  <div class="container"  ng-controller="radioController">
    <label for="redRadio">Red:</label>
    <input id="redRadio" type="radio" ng-model="colorValue" value="red" /><br />

    <label for="greenRadio">Green:</label>
    <input checked="checked" id="greenRadio" type="radio" ng-model="colorValue" value="green" /><br />

    <label for="blueRadio">Blue:</label>
    <input id="blueRadio" type="radio" ng-model="colorValue" value="blue" /><br />
    <br />
    <strong>Selected color:</strong> {{colorValue}}<br />

  </div>
<script>
angular.module("app", [])
  .controller("radioController", function ($scope)
  {

   });
</script>
</body>

2 个答案:

答案 0 :(得分:2)

您可以在单选按钮上添加ng-change功能,并将ng-model值作为参数传递。

<强>标记

<div ng-controller="radioController">
      <input type="radio" ng-model="color.name" value="red" ng-change="changedValue(color.name)">  Red <br/>
      <input type="radio" ng-model="color.name" value="green" ng-change="changedValue(color.name)"> Green <br/>
      <input type="radio" ng-model="color.name" value="blue" ng-change="changedValue(color.name)"> Blue <br/>
</div>

Demo Plunkr

为了减少html你可以使用ng-repeat指令为你呈现html,只有你应该维护一个会有各种颜色的数组。

<强>标记

<div ng-repeat="color in colors">
  <input name="radio" type="radio" ng-model="color.name" value="red" ng-change="changedValue(color.name)"> {{color.name}}
  <br/>
</div>

<强>代码

$scope.colors = [{
  name: 'Green',
  value: 'green'
}, {
  name: 'Red',
  value: 'red'
}, {
  name: 'Blue',
  value: 'blue'
}];

Updated Plunkr

答案 1 :(得分:0)

<script>
angular.module("app", [
]).controller("radioController", function ($scope, $log) {
   $scope.$watch('colorValue', function(colorValue){
       $log.info(colorValue);
   });
});
</script>