AngularJS没有显示$ scope

时间:2016-02-03 13:00:41

标签: javascript angularjs

我知道这个问题已得到解答但是解决方案对我来说并不适用。一切看起来都很好,但大括号之间的内容并没有显示在屏幕上。

    <div ng-controller="Hello">
        <p>The ID is {{greeting.ip}}</p>
        <p>The content is {{greeting.ip}}</p>
    </div>

控制器就是:

 'use strict';
angular.module('sbAdminApp')
    .controller('Hello',['$scope','$http', function ($scope, $http) {

$http.get('http://ip.jsontest.com/')
    .then(function (data) {
            $scope.greeting = data;
    console.log($scope.greeting);
        });
    }]);

在我的app.js中,我宣布:

       .state('dashboard.test', {
            templateUrl: 'views/test.html',
            url: '/test',
            controller: 'Hello',
            resolve: {
                loadMyFiles: function ($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'sbAdminApp',
                        files: ['scripts/controllers/helloWorld.js']
                    })
                }
            }
        })

我从中获取数据的JSON网址是this.

以下是控制台输出的图片:

It looks ok!

2 个答案:

答案 0 :(得分:1)

$scope.greeting = data;这一行错了。

应为$scope.greeting = data.data;

修改

因为您要将服务器的响应分配给该变量,并且只需要API调用返回的数据。您的响应对象包含标题和状态代码以及data属性等实际包含您需要的数据的id和其他内容。如果您想从响应对象中获取id,可以这样做:greeting.data.id

我总是将response变量命名为resresponse,以免弄乱它。像这样:

$http.get('http://ip.jsontest.com/')
    .then(function (res) {
            $scope.greeting = res.data;
            console.log($scope.greeting);
        });
    }]);

答案 1 :(得分:0)

问题是你正在做以下事情:

$scope.greeting = data;

但根据您的JSON,它应该是:

$scope.greeting = data.data;

data变量包含整个JSON对象,您需要来自它的数据密钥。