如何将函数中的变量传递给控制器​​?

时间:2015-04-26 02:30:19

标签: angularjs

我试图将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);
}

1 个答案:

答案 0 :(得分: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;
}

请注意,这会导致角度纯粹主义者哭泣并咬牙切齿。