简体   繁体   English

指令的角度调用控制器功能

[英]Angular call controller function from directive

I use this fancy select for Ionic http://codepen.io/mhartington/pen/CImqy ( http://jsfiddle.net/q62jx3s6/ single select!!) and I want when click on item from select to execute a function getCat from MainCtrl 我用这个花哨的选择离子http://codepen.io/mhartington/pen/CImqyhttp://jsfiddle.net/q62jx3s6/单选择!),我想,当点击从选项目执行功能getCat从MainCtrl

 $scope.getCat = function(cat) { ..... }

who can help me ?! 谁能帮我 ?! please ) And i also tried this example, but dosn't work for me ( Angular: calling controller function inside a directive link function using & ) 请)并且我也尝试了这个示例,但是对我不起作用( Angular:使用&调用指令链接函数内的控制器函数

You can define a function in MainCtrl's scope and call that function whenever you click any of the options. 您可以在MainCtrl的范围内定义一个函数,并在单击任何选项时调用该函数。

$scope.getCat = function() { //your code for getCat function }

So when you are configuring the options(or countries) you will need to configure it with an onclick attribute or ng-click like this : 因此,在配置选项(或国家/地区)时,您将需要使用onclick属性或ng-click进行配置,如下所示:

onclick = "getCat()" or ng-click="getCat()" 

Hope it helps! 希望能帮助到你!

I tried to use $scope.$watch and works now for me. 我尝试使用$ scope。$ watch并为我工作。 but i'll wait the correct answer 但我会等待正确的答案

    $scope.$watch('val', function() { if($scope.val.single != null)  $scope.getCat($scope.val.single); }, true);  

Why don't you move 'getCat' function from controller to service and then inject service to your directive ? 为什么不将'getCat'函数从控制器移至服务,然后将服务注入到指令中呢?

Calling controller function from directive is not the best solution because then the directive is tight couple with controller. 从指令中调用控制器功能不是最佳解决方案,因为指令与控制器紧密耦合。

Referring to your comment: 参考您的评论:

Maybe you could require controller in your directive, then it is injected to link function in that directive 也许您可能在指令中需要控制器,然后将其注入到该指令中的链接函数

When a directive requires a controller, it receives that controller as the fourth argument of its link function. 当指令需要控制器时,它将接收该控制器作为其链接函数的第四个参数。

This topic is described here: Angular directive in section "Creating Directives that Communicate" 这里描述了这个主题:“创建可通信的指令”部分中的Angular指令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM