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);
}
3
  • possible duplicate of Pass variables to AngularJS controller, best practice? Commented Apr 26, 2015 at 2:36
  • Where are you trying to call "showResponse" from? Commented Apr 26, 2015 at 2:37
  • I'm using the google apis client library, but I guess you can't use it with angular. Commented Apr 26, 2015 at 3:16

1 Answer 1

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.

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.