我正在尝试创建一个通用的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