2015-12-15 44 views
0

我已經編寫了自己的指令,我想從中調用父控制器上的方法。我試過在我的指令中加入require:'ngController'。但是,返回的控制器只是一個空對象。我正在運行1.4.8。如何從指令訪問ng-controller?

<div ng-controller="myController"> 
    <div my-directive></div> 
</div> 

app.directive('myDirective', function() { 
    return { 
    restrict: 'A', 
    scope: false, 
    require: '^ngController', 
    link: function (scope, $element, attrs, controller) { 
     //controller is empty object.. 
    }; 
    } 
}); 

更新:我misstake是,我添加了一個方法,控制器範圍時,我應該直接將它添加到控制器代替。

app.controller('myController', function($scope) { 
$scope.myMethod = function() {}; //Not callable from controller passed to directive 
this.myMethod = function() {}; //IS callable from controller passed to directive 
}); 

回答

0

函數需要在指令的作用域中可用。所以,如果你的指令是在控制它的範圍:

scope.fn(); 
1

您可以通過打電話的scope父控制器,如果你的指令沒有一個孤立的範圍,你不必要求ngController

angular.module('app', []) 
    .controller('controller', function($scope) { 
    $scope.greet = function() { 
     return 'hi' 
    }; 
    }) 
    .directive('testDirective', function() { 
    return { 
     restrict: 'E', 
     template: '<h1>{{ greet() }}</h1>' 
    }; 
    }); 

輸出:

hi 

Plnkr:http://plnkr.co/edit/uGXC5i1GjphcZCPDytDG?p=preview

+0

是的,這也將正常工作。除非myDirective附加到例如ng-repeat的元素上。 – ZNS

+0

你能舉個例子嗎?我還編輯了包含ng-repeats的plnkr。 – Koralarts

+0

我站在更正:)我不喜歡我的解決方案更好,因爲它更容易理解從指令調用哪個方法,而不是「鬆散耦合」。 – ZNS