0

我希望能够在我的指令“会议”中使用控制器'useSpreadsheetData'中的变量“videoUrlId”。我怎样才能做到这一点?我已经看过要求但无法使其工作。如何在指令链接功能中使用控制器中的变量?

控制器:

app.controller('useSpreadsheetData', ['$scope', '$sce', 'getSpreadsheetData',  
function($scope, $sce, getSpreadsheetData){ 
for(var x in videos) { 
     if(videos[x].switchValue) { 
     var videoUrlId = videos[x].videoUrl; 
     $scope.videoUrlId = videoUrlId; 
     break; 
     } 
    } 
}; 

指令:

app.directive('meetings', [ 'getCalendar', '$timeout', '$window', 
function(getCalendar, $timeout, $window){ 
return { 
    restrict: 'E', 
    templateUrl: 'scripts/directives/meetings.html', 
    controller: 'useSpreadsheetData', 
    link: function(scope){ 
    //Use videoUrlId variable here 
    } 
} 
}]); 
+1

您可以在链接功能与'scope.videoUrlId' – rob

+0

访问'videoUrlId'为了分享*指令之间的数据*和*控制器*或*控制器*和* *控制器,你应该使用*服务*。看看[这篇文章](http://stackoverflow.com/questions/28219403/angularjs-passing-variable-to-scope-from-directive-to-use-it-in-controller-n)和[this其他一个职位](http://stackoverflow.com/questions/12008908/angularjs-how-can-i-pass-variables-between-controllers)。 – AndreaM16

+0

@rob当我在链接函数中访问该变量时,我得到了未定义的值。 – nehas

回答

1

既然你提到你尝试内使用require,我必须承担meetings指令将是一个子元素的地方控制器,但没有看到你的HTML,我们不能确定。

如果你还没有利用isolate scope,你的指令将从上面本身父控制器,在这种情况下useSpreadsheetData prototypically继承。因此,我们可以简单地通过插入的表达式访问videoUrlId{{videoUrlId}}。请注意0​​指令中的模板。它也将分别在linkcontroller内通过scope.videoUrlId$scope.videoUrlId获得。

Plunkerhttp://plnkr.co/edit/MZIgXEiku4Z2PLzl3apz

HTML

<div ng-controller="useSpreadsheetData"> 
    Controller: <code>videoUrlId = {{videoUrlId}}</code><br> 
    Directive: <meetings></meetings> 
</div> 

的JavaScript

app.controller('useSpreadsheetData', function($scope) { 

    var videos = [service call]; 

    for (var x in videos) { 
    if (videos[x].switchValue) { 
     var videoUrlId = videos[x].videoUrl; 
     $scope.videoUrlId = videoUrlId; 
     break; 
    } 
    } 
}); 

app.directive('meetings', ['$timeout', '$window', 
    function($timeout, $window) { 
    return { 
     restrict: 'E', 
     template: '<code>videoUrlId = {{videoUrlId}}</code>' 
    } 
    } 
]); 

输出

Controller: videoUrlId = /1 
Directive: videoUrlId = /1 
相关问题