动态地将ui-sref添加到元素

时间:2015-05-21 12:36:28

标签: angularjs directive

我有以下指令

.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'}

1 个答案:

答案 0 :(得分:2)

您无法向当前正在编译的元素添加指令!原因是Angular已经已经解析它并提取了要编译的指令。相反,如果你想将一个属性指令添加到内部元素,你应该在compile函数中进行(不在preLink中 - 模板已经被编译在那里,添加属性将没有任何效果)。对于这样的情况,您希望访问范围,它将无法工作:compile无法访问范围(尚未创建)。

你能做些什么?

  1. 手动编译:

    1. ui-sref指令的模板中删除包含famAction的元素。
    2. pre-postLink中,使用$compile编译包含ui-sref的元素的模板,即以下内容:

      var uiSrefElem = $compile(
        '<button ui.sref="' + scope.action.state + '">Go!</button>'
      );
      
    3. 将此uiSrefElem添加到指令的元素中。

  2. 编程导航:将函数放在使用$state.go(scope.action.state)的范围/控制器中。单击指令元素时调用此函数。

  3. 我会选择(2)。