Nishant Nishant - 1 month ago 6
AngularJS Question

$scope assignment works in one case but in other

First Case

angular.module('tss.application').controller("UserspaceController", function($scope, $http)
{
$http(
{
url : "/dirlist",
method : "GET",
}).then(function successCallback(response)
{
$scope.lists = response;
},
function errorCallback(response)
{
window.alert("Dir list could not be get");
});

});


Second Case

angular.module('tss.application').controller("UserspaceController", function ($scope, $http)
{
$http.get('dirlist').success(function(data)
{
$scope.lists = data;
});
});


I am very new to Angularjs so this could be a stupid questions. Anyway,
the assignment of lists variable works in second case but in first. That is, the second can access the values of "lists" inside the controllers. I failed to understand what is wrong with the first case?

Answer

Try this:

angular.module('tss.application').controller("UserspaceController",  function($scope, $http)
{
        $http(
            {
                url     : "/dirlist",
                method  : "GET",
            }).then(function successCallback(response) 
            {
                $scope.lists = response.data;
            }, 
            function errorCallback(response) 
            {
                window.alert("Dir list could not be get");
            });

});

The deprecated success() method passes two separate values for data and headers, but the promise interface using .then() passes only a single response value which has the data and headers as attributes.

The change to your code is simply the line:

                $scope.lists = response.data;