How to let initiated Controller Know that scope value has changed

蓝咒 提交于 2020-01-05 03:49:04

问题


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.


回答1:


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.




回答2:


You need to define in your controller a watcher on your service value :

    $scope.$watch(function() {
        return myService.getVal();
    }, function(newVal, oldVal) {
       if(newVal !== oldVal) alert("NEW VALUE");


    });


来源:https://stackoverflow.com/questions/30325030/how-to-let-initiated-controller-know-that-scope-value-has-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!