Question

I am new to AngularJS. While trying to send formdata to Json file after click 'Add New Member' button, the new Json data overwrites the current existing Json data. I need the data to be added after the last data. I used the code below

var memberControllers = angular.module('memberControllers', []);`memberControllers.controller('addListCtrl', ['$scope', '$http',  '$location',
    function($scope, $http, $location){
        $scope.members = [];
        $scope.formData = {};
        $scope.addMember = function(){
            $http.post('data/members.json', $scope.formData).

                success(function(data){
                    console.log('added ' + data);
                    $scope.formData = {};
                    $scope.members = data;
                    $scope.members.push(data);

                })
                .error(function(data){
                    console.log('Error: ' + data);
                });
                $location.path('/members');

        /*});*/

    };

    }]);`

The result shows from Json file --->

{"id":"1","name":"Jane" }

I expect below --->

[{"id":"1","name":"Jane"},{"id":"2","name":"John"},{"id":"3","name":"Tom"}]
Was it helpful?

Solution

$scope.members = data; overwrites members - omit this line and just use push as you're doing right after.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top