简体   繁体   中英

How can i add a scope to a http controller in angular.js?

I also want to have acces to a $scope in this controller so I can do methods like ng-click and ng-change in my html. I know have this $http but i cant do anny angular function on it and I can't seem to figure out how I can use a $scope in this controller.

app.controller('songController', ['$http', function($http) {

    $songs = this;
    $songs.tracks = [];

    $http({
            url: "http://api.q-music.be/1.2/tracks/plays?limit=20",
            dataType: "jsonp",
            jsonp: "callback"
        })
        .success(function(lastSongsList) {
            $songs.tracks = lastSongsList.played_tracks;
            console.log($songs.tracks);

        });


}]);

I want to be able to do methods in this controller like this :

$scope.change = function() {
        $scope.counter++;
      };

您需要像这样注入作用域依赖性:

app.controller('songController', ['$http', '$scope', function($http, $scope) {

Change your controller definition to this:

app.controller('songController', ['$http', '$scope', function($http, $scope) {

The same way that you inject $http into your controller, you need to do the same with $scope to allow your controller to use it.

Look up dependency injection and you'll find all kinds of stuff about. It's pretty useful and you'll want to understand how it works if you're going to be working with Angular.

$songs = this;
$songs.tracks = [];

should also be

$scope.songs = this;
$scope.songs.tracks = [];

same for the $http success handler

$songs.tracks = lastSongsList.played_tracks;

should be

$scope.songs.tracks = lastSongsList.played_tracks;

Your change function can remain in the controller

$scope.change = function() {
        $scope.counter++;
      };

Then in your html, eg button input use ng-click="change()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM