view is not updated in AngularJS

血红的双手。 提交于 2019-12-11 06:36:41

问题


I have an issue when I try to display data.

  • I send my form and update my database (it works great, backend is ok)
  • I use a button on the page to return to homepage
  • The view of the homepage is not updated, always the same values. (It seems that there is only the template that loads, not with queries)

I need to click on the button refresh of the browser to see new values.

After the 'hard' refresh, the view is updated.

Why do I need to completely refresh the page ?

Here is my code

JS :

My service GenericService (I created this service because I use this in several controllers)

myApp.factory('GenericService', function ($http, $q, MyFunctions) {
    var data = {};

    function getDataIfNeeded(action) {

        action = action || 'default';

        if (data[action] !== undefined) {
            return $q.when(data[action]);
        }

        return $http({
            url: "php/functions.php",
            method: "GET",
            params: { 
                action: action, 
                dummy: MyFunctions.randomString(7)
            }
        }).then(function(response) {
            data[action] = response.data;
            return data[action];
        });
    }

    return {
        getData: getDataIfNeeded
    };
});

The call of the service

myApp.controller('listCtrl', ['$scope', '$http', '$rootScope', '$location', 'GenericService',
function ($scope, $http, $rootScope, $location, GenericService) {

  GenericService.getData("get_projects").then(function (data) {
    $scope.projects = data;
  }); 

  GenericService.getData("get_projects_draft").then(function (data) {
    $scope.projects_in_draft = data;
  }); 

 }]);

HTML :

<div ng-controller="listCtrl">
 <div ng-repeat="project in projects">
       <span>{{ project.nom }}</span>
 </div>
 <div ng-repeat="project_draft in projects_in_draft">
       <span>{{ project_draft.nom }}</span>
 </div>
</div>

回答1:


Your service GenericService fetch the data from the server only "if needed", which means if the local data variable isn't empty. Naturally, without reloading the service and after a form submission, the data will be out-of-sync! So you have two choices:

If the server is creating additional data, i.e. possesses data that AngularJS don't have after the form submission, you need to do another request in order to fetch the new data. Just empty the local data variable.

Else, if the server is just saving the data in a database for instance, and doesn't perform any other operation with an impact on what is shown on your page, you don't have to do an other request, since you already know what you sent to the server! Just update the local data variable.



来源:https://stackoverflow.com/questions/23658467/view-is-not-updated-in-angularjs

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