maskers maskers - 5 months ago 9
AngularJS Question

How do I push this new value onto array?

I have this function in my Angular controller;

$scope.addPart = function (part) {
$http.get('stock/' + this.part.oemnumber).success(function (result) {
$scope.stock = result;
});
$scope.woParts.push({"id":part.id, "name":part.partname, "partno":part.partno, "oemnumber":part.oemnumber,
"stock":part.stock, "price":stock.unitcost});
$scope.part = '';
};


It will successfully return the associated stock record and I can get stock.unitcost to output in the console and display in the view. My issue is, I need to push the value onto the woParts array.

I am getting stock undefined with the current syntax. When I try to change it to "price":$scope.stock.unitcost it does not throw an error but still does not work.

What am I missing?

I have also tried to define it before hand but that doesn't work either...

$scope.addPart = function (part) {
$http.get('stock/' + this.part.oemnumber).success(function (result) {
$scope.stock = result;
$scope.part.price = $scope.stock.unitcost;
});
$scope.woParts.push({"id":part.id, "name":part.partname, "partno":part.partno, "oemnumber":part.oemnumber,
"stock":part.stock, "price":part.price});
$scope.part = '';
};


Should I be separating the stock get and the push into 2 functions?

Thanks!

Answer

You are defining $scope.stock inside the success function, which is called async, so the next line where you push, stock is not yet initialized, as it would be initialized after the http call returns. Instead you could do:

$scope.addPart = function (part) {
        $http.get('stock/' + this.part.oemnumber).success(function (result) {
            $scope.stock = result;
            $scope.woParts.push({"id":part.id, "name":part.partname, "partno":part.partno, "oemnumber":part.oemnumber,
        "stock":part.stock, "price":stock.unitcost});
        });

    };