最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS: refresh view after location change - Stack Overflow

programmeradmin3浏览0评论

I have an application with 2 views\controller:

app.config(function ($routeProvider, $locationProvider)
{
    $routeProvider
    .when("/", {
        templateUrl: "/vw/managment",
        controller: 'managment-ctrl'
    })
    .when("/add", {
        templateUrl: "/vw/add",
        contoller: 'add-ctrl'
    })
    .otherwise({
        controller: function ()
        {
            window.location.replace('/errors/filenotfound');
        },
        template: "<div></div>"
    });

    $locationProvider.html5Mode(true);
});

The path / is my "homepage" which show a list of items from DB. In this page the user have button "Add" which redirect the page to /add. The 'Add' page allow the user to add items from DB. The user is selecting items and click "Save". The "Save" button save the items to DB and redirect back to "homepage".

$scope.save = function()
{
    // Save login...
    $location.path("/");
};

The problem

After changing the location path, the view change to "homepage" but still showing the items from time before adding the new items. Refreshing the page will solve the problem, but of course it's not the solution...

I guess that the homepage view is being loading from cache. I want to force angular refresh the view.

How to do it?

I have an application with 2 views\controller:

app.config(function ($routeProvider, $locationProvider)
{
    $routeProvider
    .when("/", {
        templateUrl: "/vw/managment",
        controller: 'managment-ctrl'
    })
    .when("/add", {
        templateUrl: "/vw/add",
        contoller: 'add-ctrl'
    })
    .otherwise({
        controller: function ()
        {
            window.location.replace('/errors/filenotfound');
        },
        template: "<div></div>"
    });

    $locationProvider.html5Mode(true);
});

The path / is my "homepage" which show a list of items from DB. In this page the user have button "Add" which redirect the page to /add. The 'Add' page allow the user to add items from DB. The user is selecting items and click "Save". The "Save" button save the items to DB and redirect back to "homepage".

$scope.save = function()
{
    // Save login...
    $location.path("/");
};

The problem

After changing the location path, the view change to "homepage" but still showing the items from time before adding the new items. Refreshing the page will solve the problem, but of course it's not the solution...

I guess that the homepage view is being loading from cache. I want to force angular refresh the view.

How to do it?

Share Improve this question edited Dec 11, 2021 at 6:10 Nimantha 6,4846 gold badges31 silver badges76 bronze badges asked Sep 24, 2017 at 6:12 No1Lives4EverNo1Lives4Ever 6,92324 gold badges90 silver badges157 bronze badges 8
  • 1 I think you should show us how you are loading the items in the homepage. – Abdullah Dibas Commented Sep 24, 2017 at 6:21
  • My server side code is creating the table and return the HTML code of the view. After redirect back to the "homepage", the server don't get GET request since the view is being loaded from cache. – No1Lives4Ever Commented Sep 24, 2017 at 6:37
  • Can you share the code of your 'managment-ctrl' ? so that we can identify the real issue. – Ushma Joshi Commented Sep 28, 2017 at 5:51
  • It seems like your service is fetching the data and caching it somehow. When you go back to your home page, the service returns that cached result from the first visit without even hitting your API again. You need to share your home controller + the service. – Vladimir Zdenek Commented Sep 29, 2017 at 12:58
  • See if stackoverflow./a/17064940/4110233 helps! – TheChetan Commented Sep 30, 2017 at 19:14
 |  Show 3 more ments

6 Answers 6

Reset to default 4

I found a few answers on this question, that might work for you. You can disable caching entirely, so the response is always fetched from the cdn/server.

One way of doing it is by modifying cache control headers from the request, so your browser wont cache the request.

app.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.mon) {
        $httpProvider.defaults.headers.mon = {};
    }
    $httpProvider.defaults.headers.mon["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.mon.Pragma = "no-cache";
    $httpProvider.defaults.headers.mon["If-Modified-Since"] = "0";
}]);

Another way is to disable caching on the particular resource, in this case your template, so just add these to the header in html file of the template.

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">

Provide whole code for the save() function that will help us to figure out issue. I think the issue is due to the asynchronous call you are calling to save the data is still in progress while you change the route state. So you can wrap the location change call in callback function of the asynchronous rest call.

You should do something like below:

$http.get("url to save").then(function success(result) {
 //your logic after save
 $location.path("/"); 
});

Try using cache: false in the route params for avoiding angular from caching the view

app.config(function ($routeProvider, $locationProvider)
{
    $routeProvider
    .when("/", {
        templateUrl: "/vw/managment",
        cache: false,
        controller: 'managment-ctrl'
    })
    .when("/add", {
        templateUrl: "/vw/add",
        contoller: 'add-ctrl'
    })
    .otherwise({
        controller: function ()
        {
            window.location.replace('/errors/filenotfound');
        },
        template: "<div></div>"
    });

    $locationProvider.html5Mode(true);
});

You can reload using $route service. You can inject this service and use reload function after redirecting. $route.reload();

If you want to perform a full refresh, you could inject $window and use that:

$scope.save = function()
{
    // Save login...
    $location.path("/");
     $route.reload();
};
$scope.save = function()
{
    // Save login...
    $location.path("/");
      $window.location.reload();
};

It happens sometime when your scope does not load properly, so you can also use $scope.$apply()

$http.post("url to save").then(function(result) {
  //your logic after save
  $location.path("/"); 
  $scope.$apply();
});

and it's better to use $state.go

and you can read more about $scope.$apply()

Hard to tell from your description as to where the caching is happening. If you look in the network tab of chrome, you can see if your app is re-fetching data from the server when the route loads, and you can see what the server is sending back. This will let you know if the problem is that the app is fetching data before the server is finished saving, or if it's even re-fetching at all.

Angular services are singletons, so they only init once. Generally, a good pattern to follow is in your controller, tell the service to fetch its data again. This way, when the route loads, your controller inits, and it fetches the data fresh every time.

发布评论

评论列表(0)

  1. 暂无评论