简体   繁体   English

我如何在angularjs中的2个独立控制器中运行功能

[英]how i can run function in 2 separated controllers in angularjs

i have 2 separate angularjs controller 我有2个单独的angularjs控制器

that named HomeController And SearchController 名为HomeController和SearchController的

i have a function that named "Search()" in HomeController 我在HomeController中有一个名为“ Search()”的函数

how can i run search function from searchController ? 如何从searchController运行搜索功能?

define the 'search' function in a factory, inject that factory into both controllers then you can access 'search' function from both controllers. 在工厂中定义“搜索”功能,将该工厂注入两个控制器中,然后就可以从两个控制器访问“搜索”功能。

sample: 样品:

app.controller('HomeController', function(searchFactory){
   //calling factory function
   //searchFactory.search();

});

app.controller('searchController ', function(searchFactory){

   //calling factory function
   //searchFactory.search();

});

app.factory('searchFacotry', function(){
  return{
    search: function(arg){
      alert('hello world');
    };
  };
});

I have made this Plunker which does the above. 我做了这个Plunker它可以完成上述。 The app.js file looks like this. app.js文件如下所示。 It uses a factory declaration. 它使用工厂声明。 Alternatively if you just want this function to store and return some data then you can use $rootScope service of angular, it is accessible globally. 另外,如果只希望此函数存储并返回一些数据,则可以使用angular的$ rootScope服务,该服务可全局访问。 Services are prefered when they are performing some operation. 当服务执行某些操作时,它们是首选。 Take a look at this Link which have answers explaining the use of services vs rootScope. 看一下此链接 ,其中包含解释服务与rootScope用法的答案。

app.controller('HomeCtrl', function($scope, searchService) {
$scope.ctrl1Fun= function() {
    searchService.search();
}
});

app.controller('SearchCtrl', function($scope, searchService) {
      $scope.ctrl2Fun= function() {
       searchService.search();
      }
})

app.factory('searchService', function(){
  function search(){
    alert('hello World')
  }
  var service = {search : search}
  return service
});

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

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