Snowman08 Snowman08 - 3 months ago 20
AngularJS Question

After post response reload data in angularjs

Question after I post my data I have a small html table that shows my data however my data doesn't show until I reload the page any help getting this to automatically show my data after I submit will be greatly appreciated.

Here is my angular_stuff

var dim = angular.module('Dim', ['ngResource']);


dim.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);

dim.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});

dim.factory("Dim", function ($resource) {


return $resource("_dims.html", { pk: 'pk' }, {
index: { method: 'GET', isArray: true, responseType: 'json' },
update: { method: 'POST', responseType: 'json' },
delete: { method: 'DELETE', headers: { 'X_METHODOVERRIDE': 'DELETE' } },
});
})


dim.service('dataService', function () {
this.data = {}
this.data.dimMap = new Array();
this.data.dimMap[""] = "description";
});


//dim.controller("DimController", function($scope, $http, Dim) {
dim.controller("DimController", function ($scope, $http, Dim) {
$scope.dims = Dim.index()
//$scope.dims = dataService.data.dimMap;

$scope.addDim = function () {
dim = Dim.save($scope.newDim)
//My guess is I need something here to reload my data ???
$scope.dims.push(Dim)
$scope.newDim = {}


}

$scope.deleteDim = function (index) {

dim = $scope.dims[index]
Dim.delete(dim)
$scope.dims.splice(index, 1);
}
$scope.newField = {};

$scope.editDim = function (field) {
window.console.log($scope.dims[field]);
$scope.editing = $scope.dims.indexOf(field);
$scope.newField[$scope.editing] = angular.copy(field);
}
})


Picture After submit
After Submit

Data only shows up if I do a manual page realod
[Manual Page Reload[2]

Answer

Dim.save is asynchronous so when you call $scope.dims.push(dim), dim is not yet saved

The solution is to use the success callback of the promise

$scope.addDim = function () { 
    Dim.save($scope.newDim).$promise.then(function(dim) {
        $scope.dims.push(dim); 
        $scope.newDim = {}; 
    });
} 
Comments