Javascript 如何在嵌套指令之间共享变量?
当一条指令(称之为Javascript 如何在嵌套指令之间共享变量?,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,当一条指令(称之为el2)嵌套在另一条指令(称之为el1)中时,我无法从el2访问el1中“本地声明”的变量(例如ng repeat、ng init等产生的变量) 。代码如下: var myApp = angular.module('myApp',[]); // define blue `el1` element which contains an `el2` child: myApp.directive('el1', function() { return { re
el2
)嵌套在另一条指令(称之为el1
)中时,我无法从el2
访问el1
中“本地声明”的变量(例如ng repeat
、ng init
等产生的变量)
。代码如下:
var myApp = angular.module('myApp',[]);
// define blue `el1` element which contains an `el2` child:
myApp.directive('el1', function() {
return {
restrict: 'E',
link: function($scope) {
},
replace: true,
template: '<div ng-init="value1 = 1;">' +
'value1: {{ value1 }}' +
' <el2></el2>' +
'</div>',
scope: {
}
};
});
// define green `el2` element:
myApp.directive('el2', function() {
return {
restrict: 'E',
link: function($scope) {
},
replace: true,
template: '<span ng-init="value2 = 2;">' +
'value1: {{ value1 || "UNDEFINED" }} value2: {{ value2 }}</span>',
scope: {
value1: '='
}
};
});
var myApp=angular.module('myApp',[]);
//定义包含“el2”子元素的蓝色“el1”元素:
myApp.directive('el1',function(){
返回{
限制:'E',
链接:功能($scope){
},
替换:正确,
模板:“”+
'value1:{{value1}}'+
' ' +
'',
范围:{
}
};
});
//定义绿色“el2”元素:
myApp.directive('el2',function(){
返回{
限制:'E',
链接:功能($scope){
},
替换:正确,
模板:“”+
'value1:{{value1 | |“未定义”}}value2:{{value2}},
范围:{
值1:“=”
}
};
});
如何访问
el2
指令中的value1
?是否有任何方法不涉及通过链接
函数或控制器
显式修改作用域?同样,问题是在两个嵌套指令之间共享一个变量
解决方案很简单,需要两个半步骤:
my var=“value1”
)scope
集合(例如scope:{myVar:'='}
)
- 确保属性名称使用了
大小写(例如破折号分隔
而不是myVar
)myVar
x.val
作为myValue1
。正如预期的那样,绑定是双向的
代码:
var myApp=angular.module('myApp',[]);
变量x={
瓦尔:1
};
//定义包含“el2”子元素的蓝色“el1”元素:
myApp.directive('el1',function(){
返回{
限制:'E',
替换:正确,
控制器:功能($scope){
$scope.x=x;
},
模板:“”+
'x.val:{x.val}}'+
' ' +
''
};
});
//定义绿色“el2”元素:
myApp.directive('el2',function(){
返回{
限制:'E',
替换:正确,
模板:“”+
'myValue1:{{myValue1 | |“未定义”}'+
'+' +
'value2:{{value2}}'+
'',
范围:{
myValue1:“=”
}
};
});
感谢go to指出,变量名可以简单地通过属性传输。el2只在el1中使用吗?如果是这样,可能有两个指令不是最好的,否则:value1可以作为属性传递吗?您在el2指令中尝试过$parent.value1吗。@Grissom这很有效!但似乎很讨厌…特别是在更复杂的情况是,它可能是父代的父代,或者你甚至不知道你的祖先给了你这个值?@FabioF。很好的解决方案。事实上,这就是我先尝试过的,然后就忘记了。问题是,在一种情况下,它不起作用,因为我忘了更改属性名称(称为
typeId
和actionType
)从camelCase到dash定界!愚蠢的我!你想发布解决方案吗?@Domi你可以用你找到的解决方案回答自己;)
var myApp = angular.module('myApp',[]);
var x = {
val: 1
};
// define blue `el1` element which contains an `el2` child:
myApp.directive('el1', function() {
return {
restrict: 'E',
replace: true,
controller: function($scope) {
$scope.x = x;
},
template: '<div>' +
'x.val: {{ x.val }}' +
' <el2 my-value1="x.val"></el2>' +
'</div>'
};
});
// define green `el2` element:
myApp.directive('el2', function() {
return {
restrict: 'E',
replace: true,
template: '<span ng-init="value2 = 2;">' +
'myValue1: {{ myValue1 || "UNDEFINED" }} ' +
'<button ng-click="myValue1 = myValue1+1;">+</button>' +
'value2: {{ value2 }}' +
'</span>',
scope: {
myValue1: '='
}
};
});