2015-05-07 67 views
2

我正在嘗試編寫一個非常簡單的指令,它涉及到基於提供的屬性之一設置屬性。我面臨的問題是attrs對象的值在link函數中沒有得到一致的認可。角度指令中'attrs'屬性無法正常工作

這裏是總計的什麼我正在努力實現:

angular.module('directives').directive('wikiNotes',function() { 
    return { 
     restrict: 'EA', 
     templateUrl: 'common/directives/wiki-notes.tpl.html', 
     link: function(scope, element, attrs) { 

      console.log(attrs.openEdit); //true 

      if(attrs.openEdit===true){ 
       console.log('open edit'); //not called 
      } 
     } 
    }; 
}); 

console.log(attrs.openEdit)被顯示爲真,但隨後在ifconsole.log是沒有得到調用。我是否錯過了一些非常明顯的東西,或者這是一個帶角度指令的怪癖嗎?

+0

我發現了這個問題。 'attrs.openEdit'被賦予'true'作爲字符串,而不是布爾值。對於跳槍和張貼道歉。 – abyrne85

+1

這是一個很好的發現。您必須將其作爲答案發布。 –

+0

所有屬性都被串行化爲一個字符串。當你想傳遞一個對現有對象實例的引用時,這可能非常煩人。 – HankScorpio

回答

1

您是否考慮在指令作用域中添加此屬性? 我認爲這是更多的Angular哲學,但這意味着你爲你的指令創建一個新的範圍。

angular.module('directives') 
.directive('wikiNotes',function() { 
    return { 
     restrict: 'EA', 
     scope: { 
      openEdit: '=' 
     }, 
     templateUrl: 'common/directives/wiki-notes.tpl.html', 
     link: function(scope) { 

      console.log(scope.openEdit); //true 

      if(scope.openEdit===true){ 
       console.log('open edit'); //should be a boolean 
      } 
     } 
    }; 
}); 

這是一個JS小提琴,演示它的工作原理。 https://jsfiddle.net/c8mn9wka/3/