所以我想说我有一个多控制器
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope', function($scope) {
//define $scope.controller1 here
$scope.controller1 = "controller1";
}).
controller('MyCtrl1', ['$scope', function($scope) {
//define $scope.controller2 here
$scope.controller2 = "controller2";
}).
controller('MyCtrl3', ['$scope', function($scope) {
//I want to get the property of $scope.controller1 and
//$scope.controller2 here
});
如上所示,例如我想从controller1访问$ scope属性,从3开始访问controller2 ...
问题是,angularjs是否能够在一个控制器上调用多个控制器?
答案 0 :(得分:0)
在AngularJS中,范围是根据它们在DOM中的位置继承的。所以如果你的HTML看起来像:
<div ng-controller="my-ctrl1">
<div ng-controller="my-ctrl2">
<div ng-controller="my-ctrl3"></div>
</div>
</div>
然后可以从MyCtrl1,MyCtrl2和MyCtrl3访问$ scope.controller1,但$ scope.controller2只能从MyCtrl2和MyCtrl3获得。
如果要在控制器之间共享数据,则应将该数据存储在服务中并将服务注入控制器:
angular.module('myApp.controllers', []).
factory('MyData', function(){
var MyData= {};
return MyData;
}).
controller('MyCtrl1', ['$scope' 'MyData', function($scope, MyData) {
MyData.controller1 = "controller1";
}).
controller('MyCtrl2', ['$scope', 'MyData', function($scope, MyData) {
MyData.controller2 = "controller2";
}).
controller('MyCtrl3', ['$scope', 'MyData', function($scope, MyData) {
// Now you can access MyData.controller1 and MyData.controller2
});