如何让启动控制器知道的范围值已更改控制器、范围

2023-09-14 23:10:39 作者:沧溟

我在AngularJS新。我有一个登入控制器,其验证用户的信息以及当成功调用服务以保存在localStorage的用户的信息和与也分配的细节是,用于检索从各个视图该用户的信息在同一个服务变量。乌兰布登录后,当我重定向用户到其他视图这已经pviously启动(造访的页面)$ P $,我将看不到新的更新的用户信息,直到我刷新页面(视图)这意味着视图不知道用户的价值在我服务的变量发生了变化。请我怎么让它知道,改变视图范围值。

Am new in AngularJS. I have a signin controller which verifies the user details and when successful calls a service to save the user details in localStorage and and also assign the details to a variable in same service that is used to retrieve that user details from various views. Buh after login when i redirect user to another view which has been previously initiated (Visted page) i will not see the new updated user details until i refresh the page(view) meaning the view does not know that the value of user variable in my service has changed. Please how do I make it know and also change the view scope value.

推荐答案

在你的控制器创建一个方法来处理刷新,即:

Create a method in your controller to handle the refresh, i.e:

$scope.refresh = function() {
  // Do things that load data here, probably with promises
};

然后用它来揭开序幕它看作是第一次装载你的控制器,即调用刷新功能在你的控制器:

Then use that to kick off loading your controller the first time it's viewed, i.e. call the refresh function in your controller:

$scope.refresh();

然后,你可以灵活地做这样的事情分配事件,迫使数据刷新,像(在你的控制器):

Then you have the flexibility to do things like assign an event to force the data to refresh, like (in your controller):

$rootScope.$on("app.refresh.foo", function() {
  $scope.refresh();
});

然后在其他地方,像广播:

Then elsewhere, broadcast like:

$rootScope.$broadcast("app.refresh.foo"); 

和如果视图已经被加载,它会调用刷新功能。

And if the view has been loaded, it'll call the refresh function.

有关此方法的一个伟大的事情是,你有你需要的刷新功能将尽可能多的东西的灵活性。您没有设置单独的观察家。

One great thing about this method is that you have the added flexibility of adding as many things as you need to to the refresh function. You don't have to set up individual watchers.