如何与一个范围共享JSON数据?

时间:2016-06-20 02:02:46

标签: javascript angularjs json

这是我的Angular控制器:

var app = angular.module('app', []);

app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
    var promise = $http.get("url1")
        .then(function (response) {
            console.log(response);
            $scope.files = [response.data]
            return $http.get('url2', {
                params: {
                    id: response.data[0].Id
                }
            })
        })
    .then(function (response2) {
        console.log(response2);
        $scope.files = response2.data;
        return response2.data;
    })
}])

我的HTML

<div ng-app="app" ng-controller="ctrl">
<script type="text/ng-template" id="category">
    <a href="{{file.Url}}"><strong>{{file.Name}}</strong></a>
    <ul ng-if="(files | filter:{ParentId : file.Id}).length > 0">
        <li ng-repeat="file in files | filter: {ParentId : file.Id" ng-include="'category'"></li>
    </ul>
</script>
<ul class="btn-highlight plus">
    <li ng-repeat="file in files | filter: {ParentId : 0}" ng-include="'category'"></li>
</ul>
</div>

我的Angular控制器中的ParentId = response.data.Id。

我的问题是我如何在我的范围内同时包含响应和响应2 $ scope.files并在我的html代码(ParentId)中调用我的response.data.Id?

2 个答案:

答案 0 :(得分:0)

尝试将范围设置在承诺之外..但无论如何,为什么在上帝的名字中你使用嵌套的promises而不是$ q服务?那回调很糟糕,而且代码很糟糕...... 使用$ q,这是它的基本用例..

var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
            $scope.files = [];
    var promise = $http.get("url1")
        .then(function (response) {
            console.log(response);
            return $http.get('url2', {
                params: {
                    id: response.data[0].Id
                }
            })
        })
    .then(function (response2) {
        console.log(response2);
        $scope.files = response2.data;
        return response2.data;
    })
}])

答案 1 :(得分:0)

您应该将代码更改为此。

var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
var promise = $http.get("url1")
    .then(function (response) {
    var response1 = [];
        console.log(response);
        response1 = response.data;
        $scope.files = [response.data]
        return $http.get('url2', {
            params: {
                id: response.data[0].Id
            }
        })
    })
.then(function (response2) {
    console.log(response2);
    var response2 = [];
    response2 = response2.data;
    var allResponse = [];
    allResponse = response2.data.concat(response1);
    $scope.files = allResponse;
    return response2.data;
})}])