使用Angular Seed进行AJAX调用

时间:2016-09-17 20:39:44

标签: angularjs ajax api binding

编辑:James P.让我确定问题似乎与CORS有关,而不一定与任何Angular代码有关。请阅读以下评论。

我对AngularJS和JS都很陌生,所以我确定这个问题的答案很简单,我已经忽略了,所以提前谢谢你。

我正在使用Angular Seed,我创建了一个经过验证的API(例如,我转到我的URL:3000 / getstuff,它显示我的mongodb的查询就好了)。

该API从包含id的3个密钥/对的mongodb返回JSON格式响应。我可以在浏览器中查看它。

所以在Angular种子中,非常基本的view1 / view1.js我修改为:

'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope', '$http', function($scope, $http) {
  //$scope.test = "test";
  //the above works when I bind in view1.html

  $http.get('http://x.x.x.x:3000/getstuff').
  success(function(response) {
    $scope.information = response;
  });

}]);

它并没有像我想象的那样起作用。因此,当我尝试在view1.html中使用简单的{{information}}绑定此响应时,它是空白的。此代码也没有破坏应用程序,它仍然有效,如果我取消注释,我可以显示{{test}}。

无论如何,任何帮助都将非常感激。为了记录,在发布之前我已经阅读了几天和几天。我只是一个新手。

1 个答案:

答案 0 :(得分:0)

您需要使用angular.copy将数据复制到$scope变量:

  $http.get('http://x.x.x.x:3000/getstuff')
            .then(function (response) {
                // Success
                angular.copy(response.data, $scope.information);
            }, function () {
                // Failure
        });

然后在你看来:

<div ng-controller="MainController">
   <div ng-repeat="item in information">
      <p>{{item.id}}</p>
      <p>{{item.type}}</p>
      <p>{{item.text}}</p>
    </div>
</div>

idtypetext是数组中每个项目的属性。

编辑:为了完整起见,以下是一个有效的示例,上面是html代码段。

(function () {

"use strict";

angular.module("app", []);

angular.module("app").controller("MainController", mainController);

function mainController($scope, $http) {

    $scope.information = [];

    $http.get("http://api.scb.se/OV0104/v1/doris/en/ssd")
          .then(function (response) {
              // Success
              angular.copy(response.data, $scope.information);
          }, function () {
              // Failure
          });

}

})();