如何从模块依赖调用函数(另一个模块) [英] how to call a function from module dependency (another module)

查看:249
本文介绍了如何从模块依赖调用函数(另一个模块)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为分页创建单独的模块,因为我需要它在不同的模块中重用,但我不知道如何从模块依赖(另一个模块)调用函数

I want to create seperate module for pagination, because I will need it to reuse in different modules, but I don't know how to call a function from module dependency (another module)

这是我的主要模块:

var App = angular.module('search', ['pagination']);

App.controller('MainController', ['$scope', '$pagination' function($scope, $pagination) {
    $scope.testFunction(); //function from pagination module controller
}])

这是我的分页模块:

var App = angular.module('pagination', []);

App.controller('PaginationController', ['$scope', function($scope) {
    $scope.testFunction = function(){
        console.log("pagination module");
    }
}])

我收到错误:

Error: [$injector:unpr] Unknown provider: $paginationProvider <- $pagination


推荐答案

要在两个模块之间共享资源,请声明工厂或服务。

To share resources across two modules, declare a factory or a service.

假设你有一个搜索模块:

Suppose you have a search module:

//you inject your pagination module here
var searchModule = angular.module('search', ['pagination']);

//and you ALSO need to inject your pagination's service into your controller
searchModule.controller('MainController', ['$scope', 'paginationSvc' function($scope, paginationSvc) {
  //function from pagination module controller
  paginationSvc.testFunction();
}])

你的分页模块:

var pagination = angular.module('pagination', []);

//declare your pagination service here
pagination.factory('PaginationSvc', [function(){
 return {
   testFunction:testFunction
 };
 function testFunction(){
   console.log('This is from pagination module');
}
}])

也许 little plnkr 会有所帮助:D

这篇关于如何从模块依赖调用函数(另一个模块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆