$scope 分配在一种情况下有效,但在其他情况下有效

$scope assignment works in one case but in other

第一个案例

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

});

第二种情况

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

我是 Angularjs 的新手,所以这可能是一个愚蠢的问题。反正, 列表变量的赋值在第二种情况下有效,但在第一种情况下有效。也就是说,第二个可以访问控制器内部 "lists" 的值。我没看懂第一种情况有什么问题?

试试这个:

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

});

已弃用的 success() 方法为数据和 headers 传递了两个单独的值,但是使用 .then() 的承诺接口仅传递了一个包含数据的 response 值和 headers 作为属性。

您的代码只需更改以下行:

                $scope.lists = response.data;
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");
            });

});

输入 $scope.lists = response.data;,会起作用