2014-11-02 24 views
0

在編譯階段,我可以訪問所有attrs元素。所以爲什麼當通過這個ATTR IM的功能我得到undefiened當傳遞到函數時,角度獲取attr undefined

這裏是代碼和plunker:

.directive('test', function() { 
    return { 
    restrict:'A', 
    compile: function(ele, attr) { 

     var div = angular.element('<div ng-show="someCond(attr.some)">directive</div>'); 

     ele.append(div) 

     return function(scope, ele, attr) { 
     scope.someCond = function(name) { 
      console.log(name); 
      return name == 'john'; 

     } 
     } 

    } 
    } 
}) 

http://plnkr.co/edit/ne4Z24VM1VmOcwAuUdCT?p=preview

回答

0

你基本上犯了兩個錯誤。

第一屬性需要被正確地連接在一起,因此該語句必須

var div = angular.element('<div ng-show="someCond('+attr.some+')">directive</div>');

其次值在HTML提供應引號內添加,因此H1應該是:

<h1 test some="'john'">test</h1>

見我plunkr

http://plnkr.co/edit/QctVj9utJ88Xss8O11ze?p=preview

+0

謝謝。我選擇了你的答案,因爲我不需要做額外的工作,並將屬性分配給@ OXMO456答案。 – Bazinga 2014-11-02 15:22:18

+0

但爲什麼我需要用這種方式寫一些=「'約翰'」,當我從鏈接函數獲取attr時,我可以像這樣做一些=「那」? – Bazinga 2014-11-02 17:30:51

+0

由於'ng-show'期望和表達。既然你需要傳遞常量表達式''''是必需的。如果我們不添加''''表達式期望值來自'$ scope.john' – Chandermani 2014-11-02 17:38:56

0

你嘗試來包裝這些所有的模塊?

;(function(window,angular,undefined){ 
    //code here 
})(window,window.angular); 

這不是什麼大不了的,但封閉性好:d

+0

爲什麼我需要這樣做?我從來不這樣做。 – Bazinga 2014-11-02 15:08:40

+0

只是隔離你的模塊代碼和防止任何可能由第三方代碼導致的錯誤的最佳做法 (抱歉,英文不是我的母語;)) – dimdimbe 2014-11-02 15:20:17

0

attr對象未在scope availlable你能做到這一點,以使現有的attr對象:

return function(scope, ele, attr) { 
     scope.attr = attr;// look here 
     scope.someCond = function(name) { 
      console.log(name); 
      return name == 'john'; 
     } 
     }