How do I properly build an AngularJS labeled radio input directive?

南笙酒味 提交于 2020-01-05 10:26:13

问题


I realize that AngularJS already has an input[radio] directive and I want to leverage that as much as possible.

I created a JSFiddle here, but I can't figure out how to get the ng-model property to work properly. I'm selecting each radio, but the selectedValue doesn't change.

Also, please tell me anything that I'm doing wrong here. I'm sure I could make some other improvements.

The HTML:

<div data-ng-controller="controller">
    <div
      data-ng-repeat="radio in radios"
      data-ng-model="selectedValue"
      data-name="radio1"
      data-label="{{radio.label}}"
      data-value="{{radio.value}}"
      data-labeled-radio></div>
    <br>
    selected value: {{selectedValue}}
</div>

The JavaScript:

angular.module('app', [])
.controller('controller', function($scope) {
    $scope.selectedValue = 'FOO';
    $scope.radios = [
        { label: 'foo', value: 'FOO' },
        { label: 'bar', value: 'BAR' }
    ];
})
.directive('labeledRadio', function(){
    return {
        require: ['ngModel', 'value'],
        restrict: 'A',
        replace: true,
        template: [
            '<label class="radio">',
            '  <input class="radio__input" type="radio" data-ng-model="ngModel" name="{{name}}" value="{{value}}">',
            '  <span class="radio__label">{{label}}</span>',
            '</label>'
        ].join(''),
        scope: {
            ngModel: '=',
            label: '@',
            name: '@',
            value: '@'
        }
    }
});

回答1:


Because of the way prototypal inheritance works in JavaScript, you can't use primatives on the scope for 2-way databinding. Therefore the way to fix this is to change selectedValue to an object...

angular.module('app', [])
.controller('controller', function($scope) {
    $scope.selectedValue = { value: 'FOO' };
    $scope.radios = [
        { label: 'foo', value: 'FOO' },
        { label: 'bar', value: 'BAR' }
    ];
})

<div data-ng-controller="controller">
    <div
      data-ng-repeat="radio in radios"
      data-ng-model="selectedValue.value"
      data-name="radio1"
      data-label="{{radio.label}}"
      data-value="{{radio.value}}"
      data-labeled-radio></div>
    <br>
    selected value: {{selectedValue.value}}
</div>

Fiddle: http://jsfiddle.net/gdnKW/

For a full explanation, see here: https://github.com/angular/angular.js/wiki/Understanding-Scopes



来源:https://stackoverflow.com/questions/23122724/how-do-i-properly-build-an-angularjs-labeled-radio-input-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!