我有以下指令
.directive('famAction', function () {
var directive = {
restrict: 'A',
scope: {action: '='},
link: link
};
function link(scope, element) {
if (scope.action.hasOwnProperty('state')) {
element.attr('ui-sref', scope.action.state);
}
if (scope.action.hasOwnProperty('func')) {
element.bind('click', scope.action.func);
}
}
return directive;
})
问题在于,在添加ui-sref
属性时,该属性不是编译的 ant因此我没有generater href
标记,因此链接不起作用。
如何动态地向元素添加ui-sref
属性然后编译它?
我甚至尝试了这个,没有成功:
.directive('famAction', function () {
var directive = {
restrict: 'A',
scope: {action: '='},
compile: compile
};
function compile(tElement, tAttrs) {
return {
pre: function preLink(scope, element, attrs) {
if (scope.action.hasOwnProperty('state')) {
element.attr('ui-sref', scope.action.state);
}
},
post: function postLink(scope, element, attrs) {
if (scope.action.hasOwnProperty('func')) {
element.bind('click', scope.action.func);
}
}
};
}
return directive;
})
PS:我的操作对象可以是以下之一:
{state: 'app.flaws.relevant', icon: 'chain-broken'}
{func: vm.ignoreFlaw, icon: 'ambulance'}
答案 0 :(得分:2)
您无法向当前正在编译的元素添加指令!原因是Angular已经已经解析它并提取了要编译的指令。相反,如果你想将一个属性指令添加到内部元素,你应该在compile
函数中进行(不在preLink
中 - 模板已经被编译在那里,添加属性将没有任何效果)。对于这样的情况,您希望访问范围,它将无法工作:compile
无法访问范围(尚未创建)。
你能做些什么?
手动编译:
ui-sref
指令的模板中删除包含famAction
的元素。在pre-
或postLink
中,使用$compile
编译包含ui-sref
的元素的模板,即以下内容:
var uiSrefElem = $compile(
'<button ui.sref="' + scope.action.state + '">Go!</button>'
);
将此uiSrefElem
添加到指令的元素中。
编程导航:将函数放在使用$state.go(scope.action.state)
的范围/控制器中。单击指令元素时调用此函数。
我会选择(2)。