2015-12-15 43 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