0

I'm trying to pass the videoUrl variable in the showResponse function into my controller. I've been trying to figure out a solution without success. Can anyone guide me in the right direction?

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

myApp.controller('mainCtrl', ['$scope', function($scope){
    $scope.videoUrl = videoUrl;
}])

// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
    var videoUrl = [];
    for (prop in response.items) {
        videoUrl[prop] = "https://www.youtube.com/embed/" + response.items[prop].snippet.resourceId.videoId;    
    }
}

// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
    gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}

// Called automatically when YouTube API interface is loaded
function onYouTubeApiLoad() {
    gapi.client.setApiKey('#######');
    search();
}

function search() {
    // Use the JavaScript client library to create a search.list() API call.
    var request = gapi.client.youtube.playlistItems.list({
        part: 'snippet',
        playlistId: '########'
    });

    // Send the request to the API server,
    // and invoke onSearchRepsonse() with the response.
    request.execute(onSearchResponse);
}

// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
    showResponse(response);
}
Grant
  • 218
  • 1
  • 5
  • 15
  • possible duplicate of [Pass variables to AngularJS controller, best practice?](http://stackoverflow.com/questions/11703477/pass-variables-to-angularjs-controller-best-practice) –  Apr 26 '15 at 02:36
  • Where are you trying to call "showResponse" from? – shivas Apr 26 '15 at 02:37
  • I'm using the google apis client library, but I guess you can't use it with angular. – Grant Apr 26 '15 at 03:16

1 Answers1

0

It would probably better/easier if you could get this stuff into angular, so that it's all happening within services. That's how data sharing is supposed to happen in angular. But maybe that's challenging due to the nature of onClientLoad. The dirty way to do it is:

Get the controller's scope directly and set it on that scope. Assuming you've got something defined like:

<div ng-controller="mainCtrl"></div>

you can get that controller's scope using jQuery:

function showResponse(response) {
  var videoUrl = [];
  for (prop in response.items) {
    videoUrl[prop] = "https://www.youtube.com/embed/" + response.items[prop].snippet.resourceId.videoId;    
  }
  var scope = $('[ng-controller="mainCtrl"]').scope();
  scope.videoUrl = videoUrl;
}

Note that this will cause angular purists to weep and gnash their teeth.

tandrewnichols
  • 3,456
  • 1
  • 28
  • 33
  • Thanks for the answer. Wanted to utilize the existing google api client library, but I guess I will try to do it the angular way. – Grant Apr 26 '15 at 03:10