从另一个控制器更新$ scope值 [英] Update $scope value from another controller

查看:81
本文介绍了从另一个控制器更新$ scope值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个侧面菜单及其控制器。在另一个控制器中,我获取用户数据并想要更新我的菜单项。怎么实现呢?我尝试使用$ watch和服务,但没有成功。另外,我从未使用过$ rootScope,所以如果不是唯一的解决方案,请避免使用。

I have a side menu and its controller. In another controller I get the user data and want to update my menu items. How to achieve that ? I tried using $watch and services but to no success. Also I never used $rootScope so please avoid if it is not the only solution.

.controller('menuCtrl', function($scope) {
    $scope.username = ""
})
.controller('afterloginCtrl', function($scope) {
var a = "this is username"      
$scope.username = a // here I wish to update username in menuCtrl
    })

如果您需要更多代码或详细信息,请与我联系。

Please let me if you need more code or details.

编辑

实际上我通过数据库表更新用户信息检索用户名和其他信息。因此菜单控制器每次都需要使用数据库中的当前值进行更新

Actually I update user info via database table, from their I am retrieving the username and other info. So menu controller needs to update with current values in database every time

推荐答案

您可以使用某些服务在控制器之间共享数据。

例如:

You can to use some service for sharing data between controllers.
For example:

.service('currentUser', () => ({data: {}, someMethod: () => {}}))
.controller('Ctrl1', (currentUser, $scope) => {$scope.user = currentUser.data;})
.controller('Ctrl2', (currentUser) => {currentUser.data.name = 'username';});

显然,您也可以使用一些适当的方法扩展您的服务。等等。

Obviously, you can also extend your service with some appropriate methods. etc.

然后你可以使用这些方法:

Then you can use these methods:

.controller('Ctrl2', (currentUser, api) => {
   api.retrieveUser()
     .then(user => currentUser.setData(user));
});

这篇关于从另一个控制器更新$ scope值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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