Search code examples
angularjsangularjs-controllerangularjs-factory

Angularjs : Call factory twice on same controller


I have the following code which is not working as expected, maybe because I am new on angular :)

I want to re-call the same factory function whenever I append a new record to my database, because that factory will give me the DB data updated in order to fulfill my html table.

The issue

The factory function getData() is not being called on the second time, so I've not been able to update my $scope.dataTable

controller code

.controller('SomeViewController', function($scope, $routeParams, getData, addData) {

//scope new record
$scope.newRecordName = "";
$scope.newRecordType = "";

//to fulfill html record's table
getData.then(function(result){
    $scope.dataTable = result
})

// submit button calls this
$scope.addRecord = function(){
    addData.record($scope.newRecordName, $scope.newRecordType).then(function(result) {
        if (result == "OK") {
            //refresh scope dataTable
            getData.then(function(result){
                $scope.dataTable = result
            })
        }
    })
}

factory code

factory('getData', function($http) {
    return $http.get('some/url/')
        .then(function(response) {
            return response
        })
})
.factory('addData', function($http) {
    return {
        record: function(name, type) {
            return $http.post('some/url', {Name: name, Type: type})
                .then(function(response) {
                    return response
                })
        }
    }
})

Note I cannot use $scope.dataTable.push( 'new_record_here' ) because its missing the record's ID from the database and I need that to have a table like: ID / Name / Type

Thank you so much


Solution

  • Change your factory to this

    .factory('dataFactory', function($http){
        return {
            getData : function() {
                return $http.get('some/url/');
            },
            addData : function(name, type){
                return $http.post('some/url/', {Name: name, Type: type});
            }
        }     
    })
    

    And your controller to this

    .controller('SomeViewController', function($scope, $routeParams, dataFactory) {
    
        //scope new record
        $scope.newRecordName = "";
        $scope.newRecordType = "";
    
        //to fulfill html record's table
        getAllData();
    
        // submit button calls this
        $scope.addRecord = function() {
            dataFactory.addData($scope.newRecordName, $scope.newRecordType).then(function(result) {
                if (result == "OK") {
                    //refresh scope dataTable
                    getAllData();
                }
            })
        };
    
        var getAllData = function() {
            dataFactory.getData.then(function(result) {
                $scope.dataTable = result
            })
        }
    })