如何在 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 中,我有:
In the HTML, I have:
<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屋!