如何在AngularJS中的两个指令之间共享作用域? [英] How do I share scope between two directives in AngularJS?
问题描述
我想在以下两个指令之间共享$scope
:
I want to share the $scope
between the following two directives:
One23SRCApp.directive('directive1',function() {
return {
restrict: "A",
scope:true,
link: function (scope, element, attrs) {
scope.tablename = "table";
}
};
});
One23SRCApp.directive('directive2',function() {
return {
restrict: "A",
link: function (scope, element, attrs) {
var tablename = scope.tablename;
}
};
})
在HTML中,我有:
<input type="text" directive2 placeholder="Search Models...">
<table directive1>
<tr>
<td>column1</td>
<td>column1</td>
</tr>
</table>
我创建了具有独立作用域的名为"directive1"的指令,将名称"table"分配给了scope.tablename
属性.我无法在其他指令中访问此范围属性.
I have created the directive named "directive1" with isolated scope, assigning the name "table" to the scope.tablename
property. I am not able access this scope property in the other directive.
那我该如何访问另一个指令的作用域?
So how can I access the scope of one directive in another?
推荐答案
您可以对需要跨指令同步的项目执行$rootScope.$broadcast
.
You can do a $rootScope.$broadcast
on items that you need to sync across directive.
或者您可以将一个对象传递给指令1隔离范围,该范围将充当通信机制.在此对象上,如果更改tablename
之类的子属性,则会影响父范围.
Or you can pass a object to your directive1 isolated scope, which would act as a communication mechanism. On this object if you change sub property like tablename
, that would affect in the parent scope.
类似
One23SRCApp.directive('directive1',function() {
return {
restrict: "A",
scope:{tableconfig:'='},
link: function (scope, element, attrs) {
scope.tableconfig.tablename= "table";
}
};
});
One23SRCApp.directive('directive2',function() {
return {
restrict: "A",
link: function (scope, element, attrs) {
var tablename = scope.tableconfig.tablename;
}
};
})
HTML变为
<table directive1 tableconfig='tableconfig'>
<tr>
<td>column1</td>
<td>column1</td>
</tr>
</table>
您的控制器应定义此对象
Your controller should have this object defined
$scope.tableconfig={};
这篇关于如何在AngularJS中的两个指令之间共享作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!