Angular, injecting own service into provider - javascript

So I am working with a provider and injecting some of angular's $log and $location service in the $get to work with them, and this works fine. However when I want to inject my own service into the provider it does not seem to work.
Here's what I mean - I can inject the angular $log and $location like so (in the provider)
this.$get = $get;
$get.$inject = ['$log', '$location'];
function $get( $log, $location) {
return {
setModule: function(name, cb) {
},
getModules: function() {
}
}
}
But, I have a service below like
.service("myService",function(){
this.sayHello = function() {
return "Hello, World!"
});
And try to inject it like
$get.$inject = ['myService', '$log', '$location'];
function $get(myService, $log, $location) {
When I call myService in the provider, it comes back undefined.
Is there any reason I can call the angular($) stuff and not my own to inject into the provider?
Thanks!
Edit : So after I inject it I try and use it inside the $get like
$get.$inject = ['myService', '$log', '$location'];
function $get(myService, $log, $location) {
return {
test: function(){
console.log(myService);
}
}
returns undefined

1) pass $injector as a dependency in the controller ['$injector']
2) call $injector.get to instantiate the service by name
$scope.service = $injector.get(servicename);

Related

How to inject a controller to a service?

Normally the service is injected in a controller.
controller.js
angular
.module('myApp')
.factory('myService', function($http){
var myService = {
get: get
};
return myService;
function get(){
// Get function.
}
});
service.js
angular
.module('myApp')
.controller('myController', function(myService) {
myService.get();
});
But it is possible to reverse the way? To Inject a controller to a service?
The straight answer would be No. You don't inject a controller to a service or anywhere else for that matter. The real question is why would you want to do that?
// Update
Assuming you are referring to https://material.angularjs.org/latest/api/service/$mdDialog.
The mdDialog service expects a controller function, you could probably pass it a reference to a function.
Example:
angular.module('app',[])
.factory('myService', function(){
return {
myMdDialogCtrl: function($scope, $mdDialog, items){
// Controller for MD Dialog
}
}
})
.controller('ctrl1', function($scope, $mdDialog, myService){
$mdDialog.show({
...
controller: myService.myMdDialogCtrl
})
})
.controller('ctrl2', function($scope, $mdDialog, myService){
$mdDialog.show({
...
controller: myService.myMdDialogCtrl
})
})

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

Trouble with Angular Resource Injection

I'm getting started with the meanjs stack, and have reached a bit of a headscratcher that I don't have the understanding to google properly.
I have the following files:
**
(function () {
'use strict';
angular
.module('students')
.controller('StudentsListController', StudentsListController);
StudentsListController.$inject = ['StudentsService'];
function StudentsListController(StudentsService) {
var vm = this;
vm.students = StudentsService.query();
}
}());
Using this service, I am able to get an array of Student objects in the list-students controller, next:
list-students.client.controller.js
(function () {
'use strict';
angular
.module('students')
.factory('StudentsService', StudentsService);
StudentsService.$inject = ['$resource'];
function StudentsService($resource) {
return $resource('api/students/:studentId', {
studentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
This works as intended.
What I don't understand, is why when I try to use the same service in another controller, it seems to fail to inject, leaving me with an undefined StudentsServices variable.
What gives?
students.client.controller.js
(function () {
'use strict';
// Students controller
angular
.module('students')
.controller('StudentsController', StudentsController);
StudentsController.$inject = ['$scope', '$state', 'Authentication', 'StudentsService'];
function StudentsController ($scope, $state, Authentication, student, StudentsService) {
var vm = this;
vm.authentication = Authentication;
vm.student = student;
vm.students = StudentsService.query();
...
}());
Your inject is wrong.
'$scope', '$state', 'Authentication', 'StudentsService'
But you're telling the controller to expect
$scope, $state, Authentication, student, StudentsService
I figured it out, per
AngularJS: Factory is always undefined when injected in controller
It was that my injections need to be in the same order as the params passed into the controller function.
Aha!

Passing Parameter to Angular Factory from controller

I couldn't pass the parameter from angular controller to factory. Can any one help me on this? It works without passing parameter but when I pass it it's not.
var app = angular.module('employee', ['ui.grid', 'ui.grid.saveState', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ui.grid.pinning', 'ui.bootstrap', 'ui.grid.autoResize','ui.grid.pagination']);
app.controller('EmpCtrl', ['$scope', '$http', '$interval', '$modal', '$log', 'gridService', function ($scope, $http, $interval, $modal, $log, gridService) {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}]);
var gridService = function ($http, $rootScope) {
return {
LoadNextPage: function (hh) {
alert(hh);
},
gridOptions:gridOptions
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
And this is how I use it in the view
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage()">
</span>
The problem is in your controller:
$scope.LoadNextPage = gridService.LoadNextPage("5");
This means that your LoadNextPage is not a function but rather a result of the call to a function in your service. Which btw doesn't return anything but rather just displays an alert. But in your view, you're using LoadNextPage as a function call...
Change it to this so your controller's LoadNextPage will be a function that you can call from the view.
$scope.LoadNextPage = gridService.LoadNextPage;
and in your view:
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage(5)">
</span>
This should work.
Note: I suspect that your gridOptions are defined somewhere outside of scope of your code that you provided in the question so that it doesn't throw and error because of the missing (likely) object. So I considered this a typo in your code and not the actual problem.
Don't want params in your view?
No problem. You can either create a wrapper function or bind it to specific parameters in your code:
// wrap
$scope.LoadNextPage = function() {
return gridService.LoadNextPage("5");
};
// bind
$scope.LoadNextPage = gridService.LoadNextPage.bind(this, 5);
Or bake the number in your service...
Issue here is gridOptions:gridOptions is not defined which throws error.
Remove ,gridOptions:gridOptions from factory.
Check snippet for working code and compare with your code.
var app = angular.module('employee', []);
app.controller('EmpCtrl', ['$scope', 'gridService', function ($scope, gridService) {
$scope.clickMe = function() {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}
}]);
var gridService = function() {
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="employee" ng-controller="EmpCtrl">
<button ng-click="clickMe()">Button</button>
</div>
you not defined gridOptions function see this link:
angular.module("myApp", []).controller("myCon", function($scope, $interval, gridService){
$scope.LoadNextPage = gridService.LoadNextPage("5");
}).factory('gridService', ['$http', '$rootScope', gridService]);
function gridService($http, $rootScope){
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
}
see this link

update angular model from a service

angular.module('app.services', []).service("test", function($http, $rootScope){
this.test=function(){
$rootScope.name="test1";
};
};
angular.module('app.controllers', []).controller('TestController', function ($scope, test) {
test.send();
})
I dont get an error but the changes don't get applied to the UI. I tried $scope.apply() and got an error.
We need to tell Angular which modules your module depends on, In our case the main module is app.controllers.
To call service from different model we need tell to controller where is our service:
['app.services']
JS
var appServices = angular.module('app.services', []);
var appCtrl = angular.module('app.controllers', ['app.services']);
appServices
.service("test", function ($http, $rootScope) {
this.send = function () {
$rootScope.name = "test1";
};
});
appCtrl.controller('TestController', function ($scope, test) {
test.send();
});
Demo Fiddle
I think you should change ".service" by ".factory".
As I can see in the creating services docs there are 3 ways of creating custom services. One of then is using factory way, as the following:
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Hope to help.

Categories

Resources