2013-12-11 54 views
5

我得到這個指令在angularJS 我可以將類屬性傳遞給angularJS中的指令模板嗎?

productApp.directive('notification', function($timeout) { 
    return { 
     restrict : 'E', 
     replace : true, 
     scope : { 
      type: "@", 
      message: "@" 
     }, 
     template : '<alert class="alert alert-type">message</alert>', 
     link : function(scope, element, attrs) { 
      $timeout(function() { 
       element.hide(); 
      }, 3000); 
     } 
    } 
}); 

這樣我就可以從這樣的觀點稱之爲:

<notification type="alert.type" message="alert.msg"></notification> 

在控制器我有定義的警報對象:

$scope.alert = { type : 'success', msg : 'This is a test'}; 

我怎樣才能動態地傳遞類型?試過了,它不起作用。如果我將alert-success傳遞給指令,它就可以工作,但我希望它是動態的。

我能夠通過這樣做來動態傳遞它嗎?

感謝

回答

4

嘗試改變指令,這一個:

productApp.directive('notification', function($timeout) { 
    return { 
     restrict : 'E', 
     replace : true, 
     scope : { 
      type: "=", 
      message: "=" 
     }, 
     template : '<alert class="alert alert-{{type}}">{{message}}</alert>', 
     link : function(scope, element, attrs) { 
      $timeout(function() { 
       // element.hide(); 
      }, 3000); 
     } 
    } 
}); 

既然你已經分離範圍內使用=於母公司scope屬性

演示Fiddle

+0

感謝它的工作!:) – msqar

+1

你也可以使用'&'創建一個單向綁定,因爲' ='是雙向的。只需將'='改爲'&',並將模板包含爲{{type()}}和'{{message()}}'。如果要防止對父範圍進行更改,或者希望能夠爲指令提供除了值之外的功能,這非常有用。 – HackedByChinese

0

在你的鏈接功能,你可以做這樣的事情 attrs.typeattrs.msg檢索傳遞給你的指令值。

+0

是的結合,但如何發送它作爲屬性警報類型的一部分作爲模板?我需要做的警報類型是動態的,嘗試從鏈接設置模板,並沒有工作:( – msqar

相關問題