【问题标题】:How do I pass the variable in a function into my controller?如何将函数中的变量传递给我的控制器?
【发布时间】:2015-07-04 13:32:54
【问题描述】:

我正在尝试将 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);
}

【问题讨论】:

标签: angularjs


【解决方案1】:

如果你能把这些东西变成角度,这可能会更好/更容易,这样这一切都发生在服务中。这就是数据共享应该以角度发生的方式。但由于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;
}

请注意,这会导致有棱角的纯粹主义者哭泣和咬牙切齿。

【讨论】:

  • 感谢您的回答。想利用现有的 google api 客户端库,但我想我会尝试以 angular 方式进行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2023-01-31
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多