我有这个:
app.controller('foo1', function ($scope) {
$scope.bar = 'foo';
});
app.controller('foo2', function ($scope) {
// want to access the $scope of foo1 here, to access bar
});
我将如何做到这一点?
答案 0 :(得分:40)
您可以使用Angular Service共享可变acrosss多个控制器。
angular.module('myApp', [])
.service('User', function () {
return {};
})
要在独立控制器之间共享数据,可以使用服务。使用需要共享的数据模型创建服务。在相应的控制器中注入服务。
function ControllerA($scope, User) {
$scope.user = User;
$scope.user.firstname = "Vinoth";
}
function ControllerB($scope, User) {
$scope.user = User;
$scope.user.lastname = "Babu";
}
答案 1 :(得分:11)
您可以使用$emit/$broadcast将数据从一个控制器范围转换为另一个控制器范围。或者只是将这些变量存储在$ rootScope上。
答案 2 :(得分:5)
app.controller('foo2', function ($scope) {
$scope.$$prevSibling.bar="bar"
});
答案 3 :(得分:0)
app.controller("firstCtrl", function ($scope) {
$scope.func = function () {
// pass scope variable(s) here
$scope.$broadcast('parentmethod', { key: value });
}
})
app.controller("secondCtrl", function ($scope) {
$scope.$on('parentmethod', function (event, args) {
// access scope variable using args
$scope.targetVar = args.key;
})
})