2015-03-31 93 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/ $#编译指令定义对象