单选按钮指令不绑定ngModel

时间:2014-02-22 10:22:32

标签: angularjs angularjs-directive angularjs-scope

我正在尝试创建一个通用的radioButton指令,该指令将从控制器中获取显示选项:

<cs-radio-field options="gender" ng-model="genderValue"></cs-radio-field>

,选项就像

$scope.gender = { label: "Gender", required:true,  valueList: [{ text: "Male", value: "yes" },{text:"Female", value:"no"}] };

该指令定义为:

app.directive("csRadioField", function () {
    var templateHtml = function () {
        return '<div ng-form="myform">' +
                '<div class="control-group" class="{{options.class}}">' +
                    '<div class="control-label">{{options.label || "Radio"}} {{ options.required ? "*" : ""}} </div>' +
                    '<div class="controls">' +
                        '<div class="radio" ng-repeat="(key, option) in options.valueList">' +
                            '<label> <input type="radio" name="myfield" ng-value="option.value" ng-model="ngModel" ng-required="options.required" />{{option.text}} </label>' +
                        '</div>' +
                        '<div class="field-validation-error" data-ng-show="myform.myfield.$invalid && myform.myfield.$dirty"> ' +
                            '<div data-ng-show="myform.myfield.$error.required">{{options.label}} is required!!!</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>';
    };

    return {
        scope: { options: '=', ngModel: '=' },
        required: ['ngModel', '^form'],
        restrict: 'E',
        template: templateHtml,
    };
});

但是ngModel在父作用域中没有绑定...主要是因为ng-repeat创建了新的作用域。

如何解决这个问题?

plunker链接:http://plnkr.co/edit/myS5hXwxjoDEqQI2q5Q7?p=preview

1 个答案:

答案 0 :(得分:8)

在模板中尝试此操作:

ng-model="$parent.ngModel"

DEMO

ng-repeat创建子范围是正确的。您实际上绑定到子范围的属性。