2015-03-31 92 views
0

有沒有什麼辦法可以將{{string}}傳遞給從$attrs(而不是$scope)獲取此屬性的指令?帶有{{}}指令屬性的角度

下面是一些代碼:

控制器:

... 
scope.someId = "someId"; 
... 

HTML:

<my-dir id="{{someId}}"></my-dir> 

指令

app.directive('myDir', function() { 
    return { 
     controller: function($attrs){ 
     console.log($attrs.id) //output: {{someId}} 
     } 
    } 
}) 

我想的是,輸出將someId而不是{{someId}}

+1

您是不是要找您要訪問的[鏈接]屬性(https://docs.angularjs.org/guide/directive#creating-a-directive -that-manipulate-the-dom)函數?他們爲什麼需要在控制器中? – 2015-03-31 16:35:05

+2

使用指令隔離範圍和雙向數據綁定有什麼問題('scope:{someId:'= id'}') – ryanyuyu 2015-03-31 16:36:20

+0

我正在用「as vm syntax」編寫我的應用程序,所以我不會使用鏈接功能。 http://toddmotto.com/digging-into-angulars-controller-as-syntax/ – vlio20 2015-03-31 16:36:46

回答

1

直到初始摘要循環被觸發,您將無法訪問$attrs中的值。一旦摘要循環被觸發,您將能夠從$attrs訪問它。

app.directive('myDir', function() { 
    return { 
     controller: function($attrs){ 
     console.log($attrs.id) //output: {{someId}} 
     $attrs.$observe('id', function (newVal, oldVal) { 
      console.log(newVal, oldVal); // here you will be able to access the evaluated value. 
     }); 
     } 
    } 
}) 
0

這裏是要做好,更專業的方式it.In angularjs有大約範圍字段中鍵入一個想法:

有3種類型的吧。

1)串@

2)功能&

3)雙向=

這種風格better.This鏈接可以幫助你。

https://docs.angularjs.org/api/ng/service/ $#編譯指令定義對象