如何为REST json数据创建基本的angularjs页面?

mem*_*und 1 javascript rest json angularjs

我正在尝试创建一个显示检索数据的基本网页http://rest-service.guides.spring.io/greeting.

json输出是:

{"id":2273,"content":"Hello, World!"}
Run Code Online (Sandbox Code Playgroud)

我正在使用以下html页面:

<body ng-app="hello">
    <div class="container">
        <h1>Greeting</h1>
        <div ng-controller="home" ng-cloak class="ng-cloak">
            <p>The Id is: {{greeting.id}}</p>
            <p>The content is: {{greeting.content}}</p>
        </div>
    </div>
    <script src="js/angular-bootstrap.js" type="text/javascript"></script>
    <script src="js/hello.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

和hello.js:

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

myApp.controller('home', ['$scope', function($scope) {
    $scope.greeting = {};

    $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data, status, headers, config) {
            $scope.greeting = data;
        });
}]);
Run Code Online (Sandbox Code Playgroud)

结果:占位符greeting.id/content未解析.这可能有什么问题?

akn*_*akn 7

你没有注射$http服务.

myApp.controller('home', ['$scope, $http', function($scope, $http) {...}]);
Run Code Online (Sandbox Code Playgroud)

编辑

在他的回答中, cverb所说的也是值得的.在Angular 1.4中,您应该替换.success().then(),因为.success已弃用.

现在用法应该是:

$http.get(url).then(
  function(data){
     //success callback
  }, 
  function(){
     //error callback
  });
);
Run Code Online (Sandbox Code Playgroud)

  • 一般说来,如果你看到你的占位符,那么angular会遇到一个错误,你可以在浏览器的js控制台中查看. (2认同)