Niebieski
Niebieski

Reputation: 609

angularJS $http.get communicating with API

I am new to AngularJS and I am trying to understand it by studying sample codes.

Here I have one about $http.get, from the following link:

http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json

I just replaced url with one of my own but it did not work, and I am really confused, please help, thanks!

=========================

second edit: thanks to the answers, double ng-app is a mistake, but it is not the main reason for this problem. I think it has something to do with cross-site blocking, but I have turn it off on my API (I use codeigniter REST API and I set $config['csrf_protection'] = FALSE; ), I am not sure how to configure it.

<!DOCTYPE html>
<html>
    <head>
        <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    </head>
    <body ng-app="myApp">
        <div ng-controller="customersCtrl">
            <ul>
                {{names}}
            </ul>
        </div>
        <div ng-controller="myCtrl">
            <ul>
                {{names}}
            </ul>
        </div>
        <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {
        $http.get("http://www.w3schools.com/website/Customers_JSON.php")
        .success(function (response) {$scope.names = response;});
        });
        app.controller('myCtrl', function($scope, $http) {
        $http.get("https://manage.pineconetassel.com/index.php/api/v1/colors2.php")
        .success(function (response) {$scope.names = response;});
        });
        </script>
    </body>
</html>

Upvotes: 0

Views: 161

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

Two ng-app directive on single page will execute the first one, 2nd one will get ignored.

Remove ng-app="myApp" from both div of your html and use angular.bootstrap to bootstrap angular app on html page using below code.

Code

angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});

Upvotes: 0

Marti Laast
Marti Laast

Reputation: 81

The problem is that you have two "myApp" declarations. From AngularJS documentation:

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.

So, you should move the ng-app="myApp" to the body element. However, once you've done that you probably still won't see any result because you are cross-site scripting and browsers will (by default) block the second request.

Upvotes: 2

Related Questions