2014-04-02 43 views
1

是否可以从自我指令编译函数访问指令名称?
只是为了更好地解释我的意思:angularjs:是否有可能从自指令编译函数访问指令名称?

app.directive('myDirective', function() { 
    return { 
    scope: {}, 
    compile: function(element, attrs) { 
     if (!attr.mandatoryParameter) return err(element, 'mandatory parameter not specified!'); 
     element.replaceWith('... ok ...'); 
    } 
    }; 

    function err(el, reason) { 
    el.replaceWith(I_WOULD_LIKE_TO_PRINT_MY_DIRECTIVE_HERE__ + ': ' + reason); 
    } 
}); 
+0

为什么你只是硬编码? – Nix

+0

我不喜欢重复代码... :-) – MarcoS

回答

2
compile: function(element, attrs) { 
    console.log(this.name); 
} 
+0

对,谢谢... – MarcoS

0

你可以将其存储在一个变量,在这种情况下,我把它在一个封闭所以它不是全局命名空间:

(function() { 
    directiveName = 'myDirective'; 

    app.directive(directiveName, function() { 
    // ... 

    function err(el, reason) { 
     el.replaceWith(directiveName + ': ' + reason); 
    } 
    }); 
})(); 
+0

对,但不是那么'优雅'... :-) – MarcoS