2016-02-25 70 views
-1
<div ng-app="myApp"> 
    <div ng-controller="FirstController"> 
    //In this controller i am having one insert Functionality on ng-click 
    </div> 
    <div ng-controller="secondController"> 
    //In this controller i am having one insert Functionality on ng-click 
    </div> 
    <div ng-controller="FinalController"> 
    //Here on ng-click i want to trigger all the other controller's click events 
    </div> 
</div> 

其实我建立一个角的js应用,在那里我有不同的部分是该用户可以保存自己输入的数据,所以出于这个原因每个控制器这里表现为单个实体,并在每个控制器的按钮点击时执行原始操作。 现在在每个控制器中都有在ng-click上实现的插入功能来将数据发送到表。在最终控制器中有一个保存按钮,我们需要触发所有不同控制器的插入点击,我如何实现这一点,任何快速建议的赞赏。我怎样才能在其他控制器调用/触发一个控制器功能角JS

+6

您可以查看这个问题: [ http://stackoverflow.com/questions/9293423/can-one-controller-call-another](http://stackoverflow.com/questions/9293423/can-one-controller-call-another) – user759863

回答

1

您可以使用$ rootScope。注入$ rootScope到所有控制器添加,然后从finalcontroller到其他控制器这样

发出一个事件在最终控制

$rootScope.$emit('triggerClick'); // when you want to trigger click in other controllers 

在firstController和secondController

$scope.yourFunction = function(){  //This will be executed on ng-click 
    // InsertFunction code 
} 

$rootScope.$on('triggerClick', function() {  // this will be executed when you trigger from finalController 
    // InsertFunction code 
}) 
+0

感谢Nijeesh它的工作就像一个魅力:) – Sultan

+0

多数民众赞成在:)很高兴为你工作:) – Nijeesh

+0

@Nigesh:当我这样做,我能够从最终控制器打它,但功能不是从他们的执行自己的控制器ex:firstcontroller – Sultan

0

你应该使用事件来在模块之间进行通信/在这种情况下,您的angularjs应用程序中的控制器。这是正确的方法。

即,使用$on, $broadcast and $emit.

Emmiter

function someFunction(){// your buttonclick or whatever you want to sstart communication with 
    $rootScope.$broadcast('eventName',{data: 100});//this should be remembered 
} 

接收机

$rootScope.$on('eventName', function(event,args){// and here is why 
    // acces with args.data 
}) 

看看这post,答案除了正确的也都是不错的潜入用于通信b中的方法/ w应用程序组件。

0

您需要从您的最终控制器广播消息,并在其他控制器上采取行动。

FinalController

function trigger(){ 
    $rootScope.$broadcast('yourEventName'); 
} 

FirstController

$rootScope.$on('yourEventName', function(){ 
    //do your insert functionality 
}) 
0

如果要触发必须使用服务的其他控制器的动作。

在服务中实现您的触发器操作,然后将其注入到另一个控制器中。

这是“最佳实践”的方式。

+0

任何例子都会帮助我更多,因为我是新的角度js – Sultan

相关问题