Angularjs : 在同一个控制器上调用工厂两次

Angularjs : Call factory twice on same controller

我有以下代码没有按预期工作,可能是因为我是 angular 的新手:)

每当我将一条新记录添加到我的数据库时,我想重新调用同一个工厂函数,因为那个工厂会给我更新的数据库数据以完成我的 html table .

问题

工厂函数 getData() 没有被第二次调用,所以我无法更新我的 $scope.dataTable

控制器代码

.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('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
                })
        }
    }
})

注意 我不能使用 $scope.dataTable.push( 'new_record_here' ) 因为它缺少数据库中记录的 ID,我需要它来获得table 喜欢: ID/姓名/类型

非常感谢

把你的工厂改成这个

.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});
        }
    }     
})

还有你的控制器

.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
        })
    }
})