简体   繁体   中英

AngularJS: Update array after submitting a new object

I need to update an array after I save an object by replacing the push method. I tried to use a function instead of the push method but it doesn't work. Any ideas on how to fix that?

app.controller("productController", function($scope, $http, createProductService, listProducstService){

    $scope.addProduct = function(){
        var newProduct = createProductService.createProduct($scope.product);
        //$scope.products.push(newProduct);     
        updateArray();
    };

    $scope.products = listProductsService.query();

    var updateArray = function(){
        $scope.products = listProductsService.query();
    }
}

app.factory("listProductsService", function($resource){
    return $resource("getAllProducts", {}, {
        listProducts: {
            method: "GET",
            isArray: true
        }
    })
})

you need to use $scope.$apply() :

var updateArray = function(){
   $scope.$apply(function () {
      $scope.products = listProductsService.query();
   });    
}

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM