javascript - 值未绑定(bind)在 Angular 自定义单选按钮组件中

标签 javascript angularjs radio-button angular-directive angular-components

我在 Angular js 中创建了一个自定义单选按钮组件,它将在我的应用程序中使用。以下是我为该组件编写的代码。

JS

angular.module("customComponent")
    .component("ngRadiobutton", {
        template:        
             '<label class="ng-control-radio-button">' +
             '  <span data-ng-bind="$ctrl.label"></span>' +
             '  <input type="radio" name="{{$ctrl.group}}" data-ng-model="$ctrl.checked"/>' +
             '  <div class="ng-control-indicator-radio"></div>' +
             '</label>' +
             '',       

        bindings: {
            label: '=?',
            checked: '=',
            group: '@'
        },
        controller: function () {
            var $ctrl = this;
            console.log($ctrl.checked);  // Data is binding properly at this stage
        }
    });

HTML

    <div data-ng-repeat="radio in vm.radioValues">
         <ng-radiobutton label="radio.label " group="group1 " checked="radio.checked"></ng-radiobutton>
    </div>

JSON

    vm.radioValues = [{ label: 'Value1', checked: true },
        { label: 'Value2', checked:false }
    ];

我面临的问题是我设置的truefalse值没有得到与组件绑定(bind)。默认情况下,两个单选按钮均未选中。谁能告诉我我的代码有什么问题。

提前致谢

最佳答案

您似乎尝试为单选按钮设置复选框行为。 (这并不是真正的绑定(bind)问题)

这是您可以拥有的有效版本:

angular.module("customComponent", [])
    .component("ngRadiobutton", {
        template:        
             '<label class="ng-control-radio-button">' +
             '  <span data-ng-bind="$ctrl.label"></span>' +
             '  <input type="radio" name="{{$ctrl.group}}" data-ng-model="$ctrl.checked" value="{{$ctrl.label}}" />' +
             '  <div class="ng-control-indicator-radio"></div>' +
             '</label>' +
             '',       

        bindings: {
            label: '=?',
            checked: '=',
            group: '@'
        },
        controller: function () {
            var $ctrl = this;
            console.log($ctrl.checked);  // Data is binding properly at this stage
        }
    });

angular.module("customComponent").controller('Ctrl', function($scope) {
  $scope.group = {value: 'Value2' };
  
  $scope.radioValues = [
      { label: 'Value1' },
      { label: 'Value2' }
    ];
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

<div ng-app="customComponent">
  <div ng-controller="Ctrl">
    <div data-ng-repeat="radio in radioValues">
         <ng-radiobutton label="radio.label" group="group1" checked="group.value"></ng-radiobutton>
    </div>
  </div>
 </div>

关于javascript - 值未绑定(bind)在 Angular 自定义单选按钮组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39913369/

相关文章:

python - 如何将单选按钮添加到 Tkinter 中的子菜单

javascript - 给出一个原始数组和一个新数组,每个元素的值表示左边更大的元素的数量

javascript - 未获取表中的表达式值

android - 将单选组添加到自定义对话框

javascript - 如何将请求参数传递回 Angular

AngularJS ng-if 具有多个条件

jQuery 将 CSS 类添加到选定的单选按钮

php - PHP 游戏中的循环迭代

javascript - forEach 内的变量范围

javascript - 通过javascript触发输入[type=file]