单选按钮ng-model为真/假(选中/未选中)

时间:2014-12-04 15:44:33

标签: javascript angularjs

我正在尝试在选择单选按钮时将单选按钮绑定为true,而在未选择单选按钮时将其绑定为false。我必须遗漏一些非常明显的东西,因为我还没能做到。

我有一个简单的集合,例如:

$scope.collection = [
    { id: 1, selected: true},
    { id: 2, selected: false},
    { id: 3, selected: false}];

我希望将“selected”属性绑定到是否选中了单选按钮。听起来很简单,但ng-model绑定到undefined。 ng-checked几乎可以工作,它显示正确的结果,但从未实际更新过值......

Plunkr with the problem

2 个答案:

答案 0 :(得分:0)

您可以将单选按钮绑定到控制器$scope中的右侧对象字段:

angular.module('ExampleApp', [])

.controller('ExampleCtrl', ['$scope', function ($scope) {
    $scope.radioContent = [
        {txt: 'One', checked: false},
        {txt: 'Two', checked: false}
    ];
    $scope.$watch('radioContent', function (now, then) {
        console.debug('Something changed', now);
    }, true);
}]);

HTML:

<div ng-app="ExampleApp" ng-controller="ExampleCtrl">
    <div ng-repeat="radio in radioContent">
        <input type="radio" ng-model="radio.checked">{{radio.txt}}
    </div>
</div>

这是一个有效的Fiddle

答案 1 :(得分:0)

似乎ng-bind和ng-selected对单选按钮效果不佳,但如果将单选按钮更改为复选框,代码将按预期工作。

使用@ Ashesh的答案,在弄乱单选按钮一次后,按钮的radio.checked属性仍然未定义。

Working plunkr

<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@*"
            data-semver="1.3.0-beta.5"
            src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script>
      angular.module("sampleapp", [])
      .controller('samplecontroller', function($scope,$rootScope) {
        $scope.collection = [
          { id: 1, selected: true},
          { id: 2, selected: false},
          { id: 3, selected: false}];
      });
    </script>

  </head>
  <body ng-app="sampleapp" ng-controller="samplecontroller">
    <div class="radio" ng-repeat="element in collection">
      <span ng-bind="element.id"></span>
      <span ng-bind="element.selected"></span>
      <input type="checkbox" name="whatever" ng-model="element.selected">
    </div>
  </body>
</html>

但是,如果您将所选属性更改为truefalse以及 "true""false",则可以使用。

相关问题