Angular.js数据源与变量

时间:2016-05-12 16:45:34

标签: javascript angularjs

当我运行以下代码时,"用户"输出正确,但似乎$ scope.users在数据源中使用时未定义。在数据源中,如果我用一个数字替换$ scope.users那么它可以工作。我做错了什么?

        $http({
            method: 'POST',
            url: '/users'
        })
        .then(function (response) {
            $scope.users = response.data.users;                                
            console.log($scope.users);
        },
        function (response) {
            console.log("Error: "+ response.data.result);
        })

        $scope.activeUsers = new kendo.data.DataSource({
            data: [
                {
                    "status": "user alive",
                    "numUsers": $scope.users,
                    "statusColor": "#dc3c3f"                        
                }
            ]
        });

1 个答案:

答案 0 :(得分:1)

可能是因为您的$scope.activeUsers请求完成之前已定义$http。请尝试以下

    $http({
        method: 'POST',
        url: '/users'
    })
    .then(function (response) {
        $scope.users = response.data.users;                                
        console.log($scope.users);
        $scope.activeUsers = new kendo.data.DataSource({
          data: [
            {
                "status": "user alive",
                "numUsers": $scope.users,
                "statusColor": "#dc3c3f"                        
            }
          ]
        });
    },
    function (response) {
        console.log("Error: "+ response.data.result);
    })