我有一个场景,我需要知道传递给函数的模型的值和名称。
我尝试了以下
$scope.rad='fff';
app.directive('kmRadio', function() {
return{
restrict:'E',
compile: function(element,attrs)
{
var model = {l:''};
model.l = attrs.kmModel;
var str1="n in ";
var str2=attrs.kmOption;
var repeat=str1.concat(str2);
var htmlText='<div><div ng-switch on="format">'+
'<div ng-switch-when="kmForm">'+
'<div>'+
'<div class="floatLeft">'+
''+attrs.title+''+
'</div>'+
'<ul>'+
'<li class="rowlist" ng-repeat="'+repeat+'"> {{n}}<input type="radio" ng-model="'+attrs.kmModel+'" name="a" ng-click="radioValueChanged(n,'+attrs.kmModel+')"/></option>'+
'</ul>'+
'{{'+attrs.kmModel+'}}'+
''+attrs.kmModel+''+
''+model.l+''+
'</div>'+
'</div>'+
'<div ng-switch-when="kmPreview">'+
'<div>'+attrs.title+'<input type="radio" ng-model="'+attrs.kmModel+'" disabled="true"/></div>'+
'</div>'+
'</div></div>';
element.replaceWith(htmlText);
}
}
})
以下代码负责调用函数
'<li class="rowlist" ng-repeat="'+repeat+'"> {{n}}<input type="radio" ng-model="'+attrs.kmModel+'" name="a" ng-click="radioValueChanged(n,'+attrs.kmModel+')"/></option>'+
$scope.radioValueChanged = function (value,model) {
//alert("Changed value"+value + model);
alert(value +" and " + model);
//alert("model "+ model );
}
在HTML中,我有一个如下代码
<km-radio km-model="rad" title="Gender" km-option="['De','CM','PM']"></km-radio>
当我点击html中的单选按钮时,我得到 o / p De和fff ,但我需要的是 o / p De和rad
请参阅the plunker code并检查指令 kmRadio
答案 0 :(得分:1)
我重写了你的指令,以获取链接函数的attributes参数的绑定:
app.directive('kmRadio', function($parse) {
return {
restrict: 'E',
replace: true,
templateUrl: 'kmRadio.html',
scope: true,
link: function(scope, element, attr) {
scope.kmModel = scope.$eval(attr.kmModel);
scope.binding = attr.kmModel;
scope.title = attr.title;
scope.kmOption = scope.$eval(attr.kmOption);
}
}
})
其中kmRadio.html
是:
<div>
<div ng-switch on="format">
<div ng-switch-when="kmForm">
<div>
<div class="floatLeft">{{title}}</div>
<ul>
<li class="rowlist" ng-repeat="n in kmOption">
{{n}} <input type="radio" ng-model="$parent.kmModel" ng-click="radioValueChanged(n, binding)" ng-value="n"/>
</li>
</ul>
bound to: {{binding}}, value: {{kmModel}}
</div>
</div>
<div ng-switch-when="kmPreview">
<div>{{title}}
<input type="radio" ng-model="kmModel" disabled="true" />
</div>
</div>
</div>
</div>
这是一个有效的演示:http://plnkr.co/edit/2q8a8B4zNGpQ0C5V1x8D?p=preview