Search code examples
angularjsrestangular

how to make global variable and print outside function


I am using AngularJS & RESTangular. Is it possible to print or get return from function from below code?

This is my controller code

var items = $scope.items = [] 
Restangular.all("items").getList().then(function(serverItems) {
    items = serverItems;
    $scope.items = serverItems
});

// PRINTING ITEMS HERE IN CONSOLE
console.log(items);
console.log(serverItems);

}

Solution

  • You can call the function by passing the $scope.items.

    var items = $scope.items = [];
    Restangular.all("items").getList().then(function(serverItems) {
        items = serverItems;
        $scope.items = serverItems;
    
        // successful getting response from the server, now print or manipulate the data
        printItems(items);
    });
    
    // PRINTING ITEMS HERE IN CONSOLE
    function printItems(items) {
        console.log(items);
        // do data manipulation
    }
    

    In this case, you will wait for getting the response, and then do the data manipulation on the response data.