2013-07-12 89 views
12

在我的控制,我定義$scope.worker這是一個簡單的JS對象:從控制器範圍傳遞變量指令

{ 
    name: 'Peter', 
    phone: 601002003 
} 

我創建了一個指令:

.directive('phoneType', [function() { 
    return { 
     restrict: 'A', 
     link: function (scope, element, attrs) { 
      console.log(attrs); 
     } 
    }; 
}]) 

和我的HTML如下像這樣:

<span phone-type="worker.phone"></span> 

我如何通過worker.phone(在這個例子601002003)在t他控制器的範圍到指令,所以我可以在link方法中創建我的邏輯? attrs.phoneType現在顯示我worker.phone字符串。

回答

27

您也可以通過兩種方式結合傳遞價值的指令:

.directive('phoneType', [function() { 
    return { 
     scope: { 
      phoneNumber: '=phoneType' 
     } 
     link: function (scope, element, attrs) { 
      // now do stuff with the number, you can access it through the scope 
      scope.phoneNumber // contains the number 
     } 
    }; 
}]) 

現在,你可以通過分離範圍直接訪問數量。 模板應該是這樣的:

<span phone-type="worker.phone"></span> 

順便說一句,你不需要限制A.這是默認的行爲。

+0

我更喜歡這個解決方案 – pixelbits

+1

我得到一個無效的密鑰錯誤 – Jordash

+0

如果worker.phone更新,scope.phoneType不會更新。有沒有解決方案? –

相關問題