【问题标题】:How can I call/trigger one controller function in other controller in Angular js [duplicate]如何在Angular js的其他控制器中调用/触发一个控制器功能[重复]
【发布时间】:2016-06-07 23:28:05
【问题描述】:
<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>

实际上,我正在构建一个 Angular js 应用程序,其中我有不同的部分,用户可以保存他输入的数据,因此,这里的每个控制器都表现为单个实体,并在每个控制器的按钮单击时执行粗略的操作。 现在就像在每个控制器中一样,在 ng-click 上实现了插入功能,以将数据发送到表中。在最终控制器中有一个保存按钮,我们需要在其中触发不同控制器的所有插入单击,我该如何实现这一点,任何快速建议都值得赞赏。

【问题讨论】:

标签: javascript html angularjs


【解决方案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
})

【讨论】:

  • 感谢 Nijeesh,它就像一个魅力 :)
  • 太好了 :) 很高兴为你解决了 :)
  • @Nigesh:当我这样做时,我可以从最终控制器中击中它,但该功能没有从他们自己的控制器执行,例如:firstcontroller
  • 此代码将添加到您已有的代码中。不要删除控制器中已有的触发功能。 rootScope.on 仅适用于从另一个控制器触发该功能时。
【解决方案2】:

您需要从您的最终控制器广播一条消息,并在其他控制器中对其进行操作。

最终控制器

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

第一控制器

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

【讨论】:

    【解决方案3】:

    如果你想触发其他控制器动作,你必须使用服务。

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

    这是做到这一点的“最佳实践”方式。

    【讨论】:

    • 任何例子都会对我有更多帮助,因为我是 Angular js 的新手
    【解决方案4】:

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

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

    发射器

    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应用程序组件通信方法的一个很好的深入了解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      相关资源
      最近更新 更多