2015-04-26 92 views
0

我试图将showResponse函数中的videoUrl变量传递给我的控制器。我一直在试图找出一个没有成功的解决方案。任何人都可以引导我在正确的方向吗?如何将函数中的变量传递给我的控制器?

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); 
} 
+0

[将变量传递给AngularJS控制器,最佳实践?](http://stackoverflow.com/questions/11703477/pass-variables-to-angularjs-controller-best-practice) –

+0

你在哪里试图呼叫“showResponse”? – shivas

+0

我正在使用谷歌apis客户端库,但我想你不能用角度来使用它。 – Grant

回答

0

它可能会更好/更容易,如果你能得到这个东西角度,所以它的所有服务中发生的事情。这就是数据共享应该如何发生的角度。但由于onClientLoad的性质,这可能是具有挑战性的。肮脏的方式是:

直接获取控制器的作用域并将其设置在该作用域上。假设你已经得到的东西定义如下:

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

,你可以使用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; 
} 

注意,这将导致角较真的哭泣和咬牙切齿。

+0

感谢您的回答。想要利用现有的谷歌API客户端库,但我想我会尽力做到这一点的角度。 – Grant

相关问题