0

I am using an API to search for songs but I just wanted to simply show 1 song from the array in my html file by using an expression in angular.js. Now I have bumped into some problems because I want to use my JSON object out of the AJAX call and in the controller.

(function() {
    var app = angular.module('songSelector', []);
    app.controller('playedTracksCtrl', function() {
        // this.songs = jsonObjectPlayedTracks;
        $.ajax({
            url: "http://api.q-music.be/1.2/tracks/plays?limit=20", 
            dataType: "jsonp", 
            jsonp: "callback", 
            success: function(jsonObject){
                //console.log(jsonObject); 
                //console.log(jsonObject["played_tracks"][0]);

                var jsonObjectPlayedTracks = jsonObject["played_tracks"];
                console.log(jsonObjectPlayedTracks);
            }
        });
    });
})();  
<!DOCTYPE html>
<html ng-app="songSelector">
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/custom.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </head>
    <body>
        <header>
            <h1 class="text-center">Vind info over de laatste 50 liedjes</h1>
            <h2 class="text-center"> - vul in - </h2>
        </header>
        <div class="list-group" ng-controller="playedTracksCtrl as overzicht">
            <div class="list-group-item">
                <h3>{{overzicht.songs[0].title}}</h3>
            </div>
        </div>
        <p>  {{"Hello, Angular!"}}  </p>  
    </body>
</html>
2
  • Can you show us an example of the returned JSON? Commented Jan 23, 2015 at 10:26
  • If you are using angular, use $http or $resource instead of jQuery. Angular is a complete framework with support for almost all things you need. jQuery is just DOM manipulation, and useful functions. Commented Jan 23, 2015 at 10:28

1 Answer 1

1

If you want to make ajax calls, you need to use $http or $resource:

(function() {

     var app = angular.module('songSelector', []);

     app.controller('playedTracksCtrl', ['songService', playedTraksCtrl]);
     app.service('songService', ['$http', songService])

     function playedTraksCtrl(songService) {
        var vm = this;

        vm.songs = {};

        songService.getPlays().then(function (data) {
          vm.songs = data;
        });
      }

      function songService($http){
        var service = {
          getPlays: getPlays
        };
        return service;

        function getPlays(){
          return $http.get('http://api.q-music.be/1.2/tracks/plays?limit=20')
          .then(function (data) {
            return data.data;
          }).catch(function (message) {
            console.log(message)
          });
        }
      }
})();

Angular sorts out the JSON for you.

I'll break it down:

function songService($http){
    var service = {
        getPlays: getPlays
    };
    return service;
}

This returns you an object:

{
    getPlays: function () {}
}

The function up there is the one we created after the return service;:

function getPlays(){
    return $http.get('http://api.q-music.be/1.2/tracks/plays?limit=20')
            .then(function (data) {
                return data.data;
            }).catch(function (message) {
                console.log(message)
            });
}

As you can see this function immediately returns the result of another function: $http.get(). The result is a Promise. A Promise says, when the result comes back fire a function off.

We need to tell that Promise what we want to do both in the service AND the controller. So in the service:

.then(function (data) {
    return data.data;
}).catch(function (message) {
    console.log(message)
});

the .then() basically says, when the Promise resolves then fire this function. The function has a parameter (or many actually but I only care about data most of the time). Data has lots of properties on it, and the one we're interested, the result of your API is data. So what we do is just return that out.

This Promise chains so then in the controller, we can call another .then(). This is fired when the one in service has finished calling.

songService.getPlays().then(function (data) {
    vm.songs = data;
});

We know by this point, that the data is just the JSON object as a JS object that we can use. So we just assign it to the vm.songs property.

Remember

A Promise is there because the call is Asynchronous, so if you see a blank space it will be because the call hasn't finished resolving. When it does, it will call that then() function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.