2013-12-09 63 views
0

我想從嵌套在另一個指令中的指令訪問控制器範圍中定義的函數。我正在使用「&」並將函數名稱作爲屬性傳遞給指令,但是我仍然無法訪問控制器作用域中的函數。在指令範圍內訪問控制器功能

有人能糾正我要去哪裏嗎?我花了幾個小時試圖發現,我必須使用「&」來達到控制器的作用範圍,但是無論我做了什麼,我都會停留在這裏。

的jsfiddle這裏 - http://jsfiddle.net/fwR9Q/12/

代碼:

<div ng-controller="PlayerCtrl"> 
<div class="col-md-4 col-sm-6 col-xs-12" ng-repeat="video in videos" > 
<tf-video src="{{video.src}}" width="{{video.width}}" handleClick="playVideo(videoId, modeNum)" height="{{video.height}}" title="{{video.title}}"/> 
</div> 
</div> 

<script> 
    var myApp = angular.module('myApp', []); 

myApp.controller('PlayerCtrl', 
    function PlayerCtrl($scope,$log, trailers) 
    { 
    $scope.videos = trailers; 
    $scope.playVideo = function(videoId, modeNum){ 
     alert("video Id = " + videoId + "; mode Num = " + modeNum); 
     return false; 
    }; 
    } 
); 

myApp.directive('tfVideo', function() { 
    return{ 
    restrict: 'AE', 
    scope: { 
     src: '@', 
     handleClick: '&', 
     width: '@width', 
     height: '@height' 
    }, 
    template: '<a href="#" ng-click="handleClick({videoId: {{src}}, modeId: modeNum{{$parent.$index}} })"><img src="http://img.youtube.com/vi/{{src}}/0.jpg" height="{{height}}" width="{{width}}"/></a>' 
    }; 
}); 

myApp.factory('trailers', function(){ 
    var trailerVideos = [ 
     { 
     src:"6kw1UVovByw", 
     width:"324", 
     height:"300" 
     }, 
     { 
     src:"uWgDVz4NEO4", 
     width:"324", 
     height:"300" 
     } 
    ]; 
return trailerVideos; 
}); 
</script> 

謝謝

+1

,因爲所有你正在使用指令生成模板做的,爲什麼你甚至需要隔離的範圍是什麼? – charlietfl

回答

2

1)在你的指令聲明:

<tf-video src="{{video.src}}" width="{{video.width}}" handleClick="playVideo(videoId, modeNum)" height="{{video.height}}" title="{{video.title}}"/> 

由於屬性使用蛇套管形式。

相反的:handleClick=

你想套管蛇:handle-click=

2)在您的模板:

template: '<a href="#" ng-click="handleClick({videoId: {{src}}, modeId: modeNum{{$parent.$index}} })"><img src="http://img.youtube.com/vi/{{src}}/0.jpg" height="{{height}}" width="{{width}}"/></a>' 

相反的:{videoId: {{src}}, modeId: modeNum{{$parent.$index}} }

你想:{videoId: src, modeNum: $parent.$index }

由於您需要使用「modeNum」參數名稱來匹配模板和指令,並且您希望直接映射到變量,而不是表達式。

Updated fiddle

相關問題