如何与AngularJs在控制器之间共享$scope,我们可以从另一个控制器访问一个控制器的$scope
How to share $scope between controllers with AngularJs can we access to one controller’s $scope from another controller?
我们可以从另一个控制器访问一个控制器的$scope吗?我需要在父、子和孙控制器中获取全部数据,这可能是吗
这是我的脚本
var app = angular.module('myApp', []);
app.controller('ParentController',ParentController);
function ParentController($scope)
{
$scope.parentName="Parent"
}
app.controller('ChildController1',ChildController1);
function ChildController1($scope)
{
$scope.childName1="Child1"
}
app.controller('ChildController2',ChildController2)
function ChildController2($scope)
{
$scope.childName2="Child2"
}
app.controller('GrandChildController1',GrandChildController1);
function GrandChildController1($scope)
{
$scope.grandChildName1="GrandChild1"
}
这是我的视图代码
<div> ng-app="myApp">
<div ng-controller="ParentController">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
<div ng-controller="ChildController1">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
<div ng-controller="GrandChildController1">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
</div>
</div>
<div ng-controller="ChildController2">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
</div>
</div>
</div>
我没有在父控制器中获得子作用域。我该怎么办。写任何服务或什么的。感谢
通过将控制器嵌套到视图中,可以实现简单的$scope
继承
<div ng-controller="a">
{{num}}
<div ng-controller="b">
{{num}}
</div>
</div>
app.controller('a', a);
function a($scope) {
$scope.num = 1
}
app.controller('b', b);
function b($scope) {
//$scope.num is inherited by the parent controller
}
您也可以始终使用$rootScope在控制器之间传递数据,通常使用$broadcast
和$emit
调度器。
相关文章:
- 如何通过AngularJS中的一个调用在多个控制器($scope)中插入相同的数据
- 门禁控制器$scope和$route指令
- 如何访问父控制器$scope子控制器中的值
- AngularJS:如何将服务方法分配给控制器$scope和ng-repeat(it)
- 控制器$scope变量在jasmine测试中未定义
- 在指令作用域和控制器$scope之间共享数据
- 尝试从AngularJS中的控制器($scope)将元素插入到视图(HTML)中
- 控制器$scope属性没有更新(套接字连接)
- Angular控制器$scope.fId显示未定义的值
- 从服务传递错误消息到控制器$scope
- 当控制器$scope变量改变时,AngularJS视图没有更新
- 子控制器$scope属性更改没有更新父控制器
- 动态更改控制器$scope变量
- 如何将异步服务中的数据设置到控制器$scope中?
- Angular控制器-scope范围
- 如何在angularJS中初始化控制器$scope变量
- UI角度模态控制器$scope值处理错误
- Angular$scope未按预期工作.正在尝试在控制器$scope和$scope.function作用域中分配对象值
- 即使控制器$scope具有新值,导航部分也不会更新
- 在$promise中使用$broadcast, mocha如何知道事件何时在控制器$scope中触发?