angular.js - Angular如何创建类似$http的全局service?
某草草
某草草 2017-05-15 17:13:05
0
2
595
  • 想写一个全局的工具类,我在独立的js文件中声明ng service(并加载到html)

(function(angular){
    "use strict";
    angular.module('testModule',function(){
        return {
            test : function(){
                console.info('testModule is ready!');
            }
        }
    });
})(window.angular);
  • 然后想在appmodule的controller里面注入testModule,但提示注入失败

var mainApp = angular.module('mainApp',[]);
mainApp.controller('homeController',['testModule',function(testModule){
  testModule.test();
}]);
"Error: [$injector:unpr] Unknown provider: testModuleProvider
某草草
某草草

reply all(2)
迷茫

Thank you, what you wrote is only 30% correct. Two topics are involved here:

1. Different modules

angular.module('testModule')angular.module('mainApp',[]) 是两个不同的module,你想要在 mainApp 中使用 testModule,那么你需要在 angular.module('mainApp', [ 'testModule' ]) Import this dependency.

2. The global tool class is written incorrectly

Someone answered it above:

(function(angular){
    "use strict";
    angular.module('testModule', []).factory('alertService', function() {
        return {
            test : function(){
                console.info('testModule is ready!');
            }
        }
    });
})(window.angular);

When in use, you can:

var mainApp = angular.module('mainApp',[ 'testModule' ]);
mainApp.controller('homeController',['alertService',function(alertService){
  alertService.test();
}]);

The above code has not been verified and there should be no structural problems. Please debug and solve it by yourself.

phpcn_u1582

Just define your service as a module, for example:

  var appServices = angular.module('myApp.services', []);
    appServices.factory('alertService', function($rootScope) {
        var alertService = {};
        return alertService;
    });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!