我有一个使用单选按钮编译模板的指令。 我试图在编译后让孩子们出现并且没有显示出来。 我哪里错了?
<div radiolist></div>
JS
app.directive('radiolist', function() {
var templateHtml = function () {
return '<label ng-repeat="option in options" > <input type="radio" ng-disabled="{{isDisabled}}" name="{{attributename}}" ng-value="option.Value" ng-model="$parent.ngModel" />{{option.Desc}} </label>';
};
return {
template: templateHtml,
link : function(scope, element) {
scope.options = [
{
"Value" : "Y",
"Desc" : "Yes"
},
{
"Value" : "N",
"Desc" : "No"
}
]
console.log(angular.element(element).children())
}
};
});
答案 0 :(得分:0)
您无法看到孩子的原因是因为当调用link函数时,指令刚刚完成编译。没有孩子,因为ng-repeat还没有机会渲染任何东西。
我建议您重新构建代码,以便不必访问子代,我假设您想要将侦听器添加到单选按钮。尝试明确定义每个单选按钮而不是使用ng-repeat。
最后,元素已经是一个角元素,你不需要再次包装它。修复代码中的那一行以继续调试。
编辑:
你的plunkr的mod可以帮助你处理事件绑定,我添加了ng-click到ng-repeat的渲染元素,然后传递了radiobutton的索引:
http://plnkr.co/edit/fABRl8OGMywsilmo9m8e?p=preview
app.directive('radiolist', function() {
var templateHtml = function () {
return '<label ng-repeat="option in options" >' +
'<input ng-click="someFunction($index)" type="radio" ng-disabled="{{isDisabled}}" name="{{attributename}}" ' +
'ng-value="option.Value" ng-model="$parent.ngModel" />{{option.Desc}} </label>';
};
return {
template: templateHtml,
link : function(scope, element) {
scope.options = [
{
"Value" : "Y",
"Desc" : "Yes"
},
{
"Value" : "N",
"Desc" : "No"
}
]
scope.someFunction = function(index) {
console.log('clicked:', index);
}
// Don't fix this, but at least don't wrap element again
console.log('children:', element.children());
}
};
});