Cherry
Cherry

Reputation: 1041

How to show new data on page after saving AngularJS

I am putting some names in a form and trying to show them alphabetically after saving. Here is the method which has all the saved data. response.data should have all the saved data:

function refreshNames() {
   NameService.getNames().then(function(response) {
      $scope.names = _.sortBy(response.data, "bank_name");
         console.log($scope.names);
      });
}
refreshNames(); //this method shows already saved names

Here in the saveButton function I am calling the above function and expecting to see the newly saved name with the older names. But it does not show in the list.

  $scope.saveButton = function() {
    var name_id = _.pluck($scope.newNames, "NameID");
    ClipMetadataService.saveNames(station_id, $scope.newTemplateFields).then(
                function(response) {
            NameService.getNames().then(function(response) {
               // $scope.names = _.sortBy($scope.names.concat(response.data),
                     "bank_name");// this shows the newly added name in the list, but I am trying to use the refreshNames() method other than doing this
               console.log(response.data);//has the newly added name
               refreshNames();// this method DOES NOT show the newly added name in the list
            });
            };

Putting $scope.names = _.sortBy($scope.names.concat(response.data), "bank_name"); in the saveButton method shows the newly added name in the list but I am trying to use refreshNames() method to do this. How can I modify the method to add the newly added response.data?

Upvotes: 0

Views: 54

Answers (1)

Abhidev
Abhidev

Reputation: 7253

No need to make calls in both the methods, separate the functionality. Check the code below:-

function refreshNames(data) {
   $scope.names = _.sortBy(response.data, "bank_name");
}

$scope.saveButton = function() {
   NameService.getNames().then(function(response) {
   refreshNames(response.data);// pass the response to the refreshNames method to sort them
   });
};
refreshNames();

Upvotes: 1

Related Questions