Tom V Tom V - 2 months ago 14
Ajax Question

AJAX call using Angular Seed

Edit: James P. led me to determine that the issue appears to be with CORS and not necessarily with any of the Angular code. Please read comments below.

I am very new to AngularJS and JS altogether, so I'm sure the answer to this is something simple that I have overlooked so thank you in advance.

I am using Angular Seed and I have created an API that is verified working (as in, I go to my URL:3000/getstuff and it displays queries from my mongodb just fine).

That API returns a JSON format response from a mongodb with 3 key/pairs including id. I am able to view it in browser just fine.

So in Angular seed, very basic view1/view1.js I modified to as such:

'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;
});

}]);


And it is not working as I thought it might. So when I try to bind this response in view1.html with a simple {{information}} it's blank. This code did not break the app either, it still works and I am able to display {{test}} if I uncomment it.

Anyhow, any help would be very much appreciated. And for the record, I have been reading up on this for days and days before posting this. I am just a novice is all.

Answer

You need to use angular.copy to copy the data to your $scope variable:

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

Then in your view:

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

Where id and text are properties of each item in the Array.

Comments