如何在两个指令中AngularJs之间共享范围 [英] How to share scope between two directive in AngularJs
问题描述
我要两个指令之间共享$范围内,我已经下面的两个指令
I want share $scope between two directive, i have following two directive
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>
我已经创建了指令名字为指令1与孤立的范围,住在我指定表名scope.tablename属性,我不能够访问另一个指令此作用域属性。
i have created directive name as "directive1" with isolated scope, in that i have assign table name to scope.tablename property, which i am not able access this scope property in another directive.
因此,如何我可以访问一个指令的范围,另一个?
So how i can access scope of one directive in another?
推荐答案
您可以做一个 $ rootScope。$广播
在您需要跨指令。同步项目
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屋!