有没有办法通过$ controller将一个范围从一个控制器继承到另一个控制器?
这是我目前的代码:
var peopleApp = angular.module('peopleApp', []);
peopleApp.controller('indexController', function($scope){
$scope.sampleVar = "Hello World";
$scope.sampleVar2 = "Hello World Again";
});
peopleApp.controller('addController', function($scope, $controller){
$controller('indexController', {$scope.sampleVar: $scope.sampleVar});
alert($scope.sampleVar);
});
我知道这会因为" $ controller(' indexController',{$ scope.sampleVar:$ scope.sampleVar})而引发错误;"应该是" $ controller(' indexController',{$ scope:$ scope});"但是那里有概念或期望的回报。
答案 0 :(得分:0)
<body ng-controller="parentController">
<div ng-controller="childController1">
</div>
<div ng-controller="childController2">
</div>
</body>
您可以从父控制器继承属性到childController1和childController2
Angularjs通过ng-controller指令在内部维护范围层次结构,您在dom中定义。对于https://docs.angularjs.org/guide/controller
中的更多详情另一种方法是Inject $ rootScope内部控制器和访问属性 应用程序控制器中的任何位置
var app = angular.module('sample',[])
app.controller('controller1',function($rootScope,$scope){
$rootScope.parent ="I am visible in any controller";
})
app.controller('controller2',function($rootScope,$scope){
//here you can access rootScope property using rootScope or Scope
// Because rootScope is parent for all scope object
// Angular scope protochain is like javascript protochain it looks from child to parent scope
console.log( $rootScope.parent);
console.log($scope.parent);
})