我如何从另一个访问一个控制器的范围$变量Angular.js? [英] How do I access the $scope variable of one controller from another in Angular.js?

查看:267
本文介绍了我如何从另一个访问一个控制器的范围$变量Angular.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的:

app.controller('foo1', function ($scope) {
  $scope.bar = 'foo';
});
app.controller('foo2', function ($scope) {
  // want to access the $scope of foo1 here, to access bar
});

我将如何做到这一点?

How would I accomplish this?

推荐答案

您可以使用一个角服务共享变量acrosss多个控制器。

You could use an Angular Service to share variable acrosss multiple controllers.

angular.module('myApp', [])
.service('User', function () {
    return {};
})

要共享独立控制器当中的数据,可以使用服务。创建需要被共享数据模型中的服务。注入该服务中的各个控制器

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

function ControllerA($scope, User) {
    $scope.user = User;
    $scope.user.firstname = "Vinoth";
}

function ControllerB($scope, User) {
    $scope.user = User;
    $scope.user.lastname = "Babu";        
}

这篇关于我如何从另一个访问一个控制器的范围$变量Angular.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆