Javascript Angularjs:如何将范围变量传递给指令?
我正在尝试使用指令创建多个标记并将其附加到Javascript Angularjs:如何将范围变量传递给指令?,javascript,angularjs,scope,directive,Javascript,Angularjs,Scope,Directive,我正在尝试使用指令创建多个标记并将其附加到中,如下所示: module.directive('createControl', function(){ return function(scope, element, attrs){ console.log(attrs.createControl); // undefined } });
中,如下所示:
module.directive('createControl', function(){
return function(scope, element, attrs){
console.log(attrs.createControl); // undefined
}
});
<div class="control-group" ng-repeat="(k, v) in selectedControls">
<div create-control="{{ v.type }}"></div>
</div>
但是当我尝试使用attrs.createControl时,我得到了未定义的代码,我不明白为什么。实际问题:如何将范围变量传递给指令?读取属性/观察插值属性。在链接阶段,尚未设置属性 有几种方法,包括使用
attrs.$observe
或$timeout
app.directive('createControl', function($timeout){
return function(scope, element, attrs){
attrs.$observe('createControl',function(){
console.log(' type:',attrs.createControl);
element.text('Directive text, type is: '+attrs.createControl);
});
}
}) ;
app.directive('createControl',function(){
返回{
范围:{
createControl:“=”
},
链接:函数(作用域、元素、属性){
element.text(scope.createControl);
}
}
})
如果v.type
可能会更改(即,您确实需要使用插值--{}}),请使用@charlietfl或@Joe的answser,具体取决于您希望指令具有的作用域类型
如果v.type
不会更改(即,链接函数只需获取一次值,并且这些值保证在链接函数运行时设置),则可以使用或。这有一点性能优势,因为没有创建$watchs。(使用$observe()
和=
,Angular设置$watchs,每个摘要周期对其进行评估。)
我不太确定我得到了这个,现在div是指令了吗?Jackie,Angular正在寻找一个与
创建控件
(连字符小写)属性匹配的指令(camelCase)。解释可能会帮助其他人:1.“@”
无论出于何种原因都无法工作。2.)也可以使用多个变量应用,如
。请注意,valueTwo
在指令范围定义(valueTwo
)中也变成camelCase。3.)变量周围不能有{{}
(例如,no..=“{v.type}}”
)
app.directive('createControl', function($timeout){
return function(scope, element, attrs){
attrs.$observe('createControl',function(){
console.log(' type:',attrs.createControl);
element.text('Directive text, type is: '+attrs.createControl);
});
}
}) ;
app.directive('createControl', function() {
return {
scope: {
createControl:'='
},
link: function(scope, element, attrs){
element.text(scope.createControl);
}
}
})
<div class="control-group" ng-repeat="v in [{type:'green'}, {type:'brown'}]">
<div create-control="v.type"></div>
</div>
<div create-control="v.type"></div>