javascript - AngularJs: Calling Service/Provider from app.config -
i call service within app.config.
when searching this, found this question solution tried follow (not accepted answer, solution below title "set service custom angularjs provider")
however solution , suggested alternative run problems when trying call service within app.config (the service not seem called @ all). new angular , javascript , don't know how debug (i using firebug). hope can me pointers , possibly solution.
current code (trying implement "possible alternative" linked question:
angular.module('myapp', [ 'ngroute', ]) .config(['$routeprovider', '$locationprovider', '$provide', function($routeprovider, $locationprovider, $provide) { $provide.service('routingservice',function($routeparams){ var name = $routeparams.name; if (name == '') {name = 'testfile'} var routedef = {}; routedef.templateurl = 'pages/' + name + '/' + name + '.html'; routedef.controller = name + 'ctrl'; return routedef; }) //here hold of returned routedef object defined above. $routeprovider.when('/name:', { templateurl: routingservice.templateurl, controller: routingservice.controller });
my previous attempt declare service via provider:
var servicemodule = angular.module('routingservicemodule', []); servicemodule.provider('routingservice', function routingserviceprovider(){ this.$get = [function routingservicefactory(){ return new routingservice(); }] }); function routingservice(){ this.geturlandcontrollerfromrouteparams = function($routeparams){ var name = $routeparams.name; var routedef = {}; routedef.templateurl = 'pages/' + name + '/' + name + '.html'; routedef.controller = name + 'ctrl'; return routedef; } }
and tried call call service in controller (after adding routingservicemodel
dependencies of myapp
of course). in both cases templateurl , controller not set when navigate views, guess missing dependencies, or not calling service correctly.
any ideas?
during config phase, providers can injected (with exception of services in auto module--$provide , $injector).
please check working demo: http://jsfiddle.net/nxbl66p2/
angular.module('joy',[]) .config(function($provide) { $provide.provider('greeting', function() { this.$get = function() { return function(name) { alert("hello, " + name); }; }; }); }) .controller('myctrl', ['$scope', 'greeting', function ($scope, greeting) { $scope.greet = function () { greeting('joy'); }; }]);
simple html:
<div ng-app="joy"> <div ng-controller="myctrl"> <div ng-click="greet()">click greet.</div> </div> </div>
reference: https://github.com/angular/angular.js/wiki/understanding-dependency-injection
Comments
Post a Comment