S
S
studio7am2014-07-17 15:30:43
Angular
studio7am, 2014-07-17 15:30:43

Angular.js - Is it possible to take data from a json file by url?

I recently started learning angular and, like many others, I started with a tutorial on angular.ru. The tutorial explains step by step how to display a list of phones with a description in html from a json file. (PhonecatApp).

var phonecatApp = angular.module('phonecatApp', []);
                 phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
                $http.get('phones/phones.json').success(function(data) {
                $scope.phones = data;
              });
            $scope.orderProp = 'age';
             });

This code in the controller, using the $http service, extracts the title and body from the json file, which lies nearby in the phones/phones.json folder and displays it in html.
Question. Is it possible to take data from a json file that is not located locally, but for example by url?
For the experiment, I wrote a simple rails app that generates json https://secret-coast-8851.herokuapp.com/phones.json
And tried this:
var phonecatApp = angular.module('phonecatApp', []);
                 phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
                $http.get('https://secret-coast-8851.herokuapp.com/phones.json ').success(function(data) {
                $scope.phones = data;
              });
            $scope.orderProp = 'age';
             });

But nothing happened. In fact, both there and there json file. The file structure is the same. Why doesn't it work? There are options. Tell me - I'll be grateful.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
B
buurz, 2014-09-18
@studio7am

As already mentioned, you need to use jsonp. And do not forget about JSON_CALLBACK
In my application it is used like this:

$http.jsonp(url+'&callback=JSON_CALLBACK') # url = Ваш url
.success(data)->
 #some code
.error(data) ->
 #some code

D
Denis Pushkarev, 2014-07-17
@rock

If the backend is yours and the domain is different from what the client is taken from, use jsonp . Angular works great with it.

S
Sergey, 2014-07-17
Protko @Fesor

Either start the static server from localhost, or start the browser (chrome) with --disable-web-security

R
Ruslan Lopatin, 2014-07-18
@lorus

Remove the space at the end of the address ' https://secret-coast-8851.herokuapp.com/phones.json '

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question