2014-04-02 45 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