如何在 AngularJS 中与另一个控制器共享 $scope 变量? [英] How to share the $scope variable of one controller with another in AngularJS?

查看:28
本文介绍了如何在 AngularJS 中与另一个控制器共享 $scope 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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

我将如何做到这一点?

推荐答案

您可以使用 Angular Service 在多个控制器之间共享变量.

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";        
}

这篇关于如何在 AngularJS 中与另一个控制器共享 $scope 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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