DiPix DiPix - 6 months ago 15
AngularJS Question

I have to click twice to add / remove item because of IE Cache with AngularJS

I have an application built with Node.js and AngularJS. And I am making simple CRUD operations.
In chrome, everything works fine, but in Internet Explorer, because of cache, I have to refresh data manually.

After a few hours I found a solution but it still doesn't work 100%.
For example:


  1. Enter the name in the textbox ("Partner_name_1") and press
    Add

  2. Nothing happens

  3. Again enter the name in the textbox ("Partner_name_2") and press
    Add
    (or just simply refresh the page)

  4. On the list below appears ("Partner_name_1")

  5. ...and you can repeat from the beginning



Here is my code

View:

form(name="AddPartner")
|Name:
input(type='text', name='name' ng-model="dataPartner.name")

button(type='add', ng-click="addPartner(dataPartner)")
| Add


table(style="width:100%")
tr(ng-repeat="partner in partnerList")
td
p {{ partner.name }}
td
button(type='remove', ng-click="removePartner(partner._id)")
| Remove


Angular script:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';
}]);

myApp.controller("myCtrl", function($scope, $http, $timeout){


$scope.loadPartnersData = function () {
$http.get("/main/partner-list").then(function(result) {
$scope.partnerList = result.data.partnerList;
});
};
$scope.loadPartnersData();

var addPartner = '/main/addPartner'
var removePartner = '/main/removePartner'

$scope.addPartner = function(data) {
$http.post(addPartner, data)
.then(function(response) {
console.log(response);
$timeout($scope.loadPartnersData(), 5000)
});
};

$scope.removePartner = function(id) {
var data = {"id": id}
$http.post(removePartner, data)
.then(function(response) {
console.log(response);
});
$scope.loadPartnersData();
};
});





@EDIT

Probably the problem is in backend, but i dont't see any.

router.post('/addPartner', function (req, res) {
new Partner({ name : req.body.name, shared : req.body.shared }).save(function (err) {
if (err) console.log(err);
res.writeHead(200, { 'Content-Type': 'application/json' });
});
});

Answer

Try this:

 $scope.addPartner = function(data) {
    $http.post(addPartner, data)
        .then(function(response) {
            console.log(response);
            $scope.loadPartnersData();
        });
};

You were calling loadPartnersData() outside the http post promise, that caused it to run right away, probably before the add actually processed in the backend.

Will want to fix the remove, it has the same issue.