How to use service in angular.js controller? - angularjs

I have created the service but i am not getting how use this service in my controller.
(function(){
'use.strict';
angular
.module('app.core')
.factory('shareBtwnCtrlr', shareBtwnCtrlrService);
/** #ngInject */
function shareBtwnCtrlrService() {
shareBtwnCtrlr = function($scope, $rootScope){
$scope.value = $rootScope.test;
}
return shareBtwnCtrlr;
}
})();
In the above code $rootScope.test is coming from one controller and now i have to use this $scope.value in another controller using this service. The another controller is like below
(function (){
'use strict';
angular.module('app.product')
.controller('ProductController', ProductController);
/** #ngInject */
//ProductController.$inject = ['$http', '$location', '$scope'];
function ProductController($http, $location, $rootScope, $scope, $localStorage, $interval, $timeout,$mdDialog, $document, shareBtwnCtrlr){
var vm = this;
}
})();

You got two modules, so dependency injector can't inject your service from app.core to app.product.
Try to create new module
var app = angular.module('app', ['app.core','app.product']);
and then
angular.module('app').factory('shareBtwnCtrlr', shareBtwnCtrlrService);

Only a service in the same module can be injected to the controllers and directives of the module.
The new module should be added to the app to expand its capabilities.
angular.module('app.core')
.factory('shareBtwnCtrlrService', function() {
var shareBtwnCtrlrService = this;
shareBtwnCtrlrService.value = function(){
//do something
}
return shareBtwnCtrlrService;
}
};
angular.module('app.product')
.factory('productService', function() {
var productService = this;
productService.value = function(){
//do something
}
return productService;
}
};
Now to use the service in the core and product modules, we create app module including both in it
angular.module('app', ['app.product', 'app.core'])
.controller('ProductController', ['shareBtwnCtrlrService', 'productService', function (shareBtwnCtrlrService, productService) {
// ...do something
}]);

Related

Angular controller Function not defined

I have tried creating a controller using meanjs.org. The controller is working fine with the other existing controllers but it is not working fine with new one I have created, Help would be appreciated, Thank you.
angular.js:12808 Error: [ng:areq] Argument
'TestownerControllerController' is not a function, got undefined
http://errors.angularjs.org/1.4.14/ng/areq?p0=TestownerControllerController&p1=not%20aNaNunction%2C%20got%20undefined
this is my controller code
(function() {
'use strict';
angular.module('users').controller('TestownerControllerController', TestownerControllerController);
TestownerControllerController.$inject = ['$scope'];
function TestownerControllerController($scope) {
var vm = this;
// Testowner controller controller logic
// ...
init();
function init() {
}
}
})();
In your case you miss [] where you define user app angular.module('users')...
[]: it's required and we use it to inject other modules.
also you can set a config in your app like this:
app.config(["$controllerProvider", "$compileProvider", "$filterProvider", "$provide", function ($stateProvider, configs, $controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
}]);
This config help you to register a module with others dependencies.
//our main app
var app = angular.module('users', [])
//our controller
function testController($scope) {
function init() {
//somthing
}
init();
}
testController.$inject = ['$scope'];
app.controller('testController', testController);

Angularjs: Injecting one controller in another failed

I have this controller A which I'm trying to inject in every other controller.
What controller A does is, it communicates with a factory (which does some authentication services, communicates with database)
My factory looks like this and I named it myFactoryServices.js and included the link to it in my index page.
(function() {
angular
.module('myApp.myFactoryServices', [])
.factory('FactoryService', ["$http", "$location", function($http, $location){
var my = this;
my.someFunction = function()
{
//communiate with backend and return data
}
return my;
}]);
})();
and my Controller A looks like this:
(function() {
angular
.module('myApp.ControlA', [])
.controller('ControllerA', function($scope,$routeParams, FactoryService) {
var my = this;
FactoryService.someFunction();
});
})();
And I am trying to inject this controller in every other controller, but it does not work. I am pretty new to this kind of programming, can anyone tell me where I made mistake?
This is how I tried injecting a controller into another.
(function() {
angular
.module('myApp.ControlB', [])
.factory('ControllerBService', function($http) {
var baseUrl = 'backendurl/';
return {
getInfo: function() {
return $http.get(baseUrl+ 'getInfo');
}
};
})
.controller('ControllerB', function($scope,$routeParams, ControllerBService,ControllerA) {
var my = this;
});
})();
No error is coming, and the controller is not getting injected as I am not able to use those factory services. is this the correct method?
First of all you cannot inject controller to another controller, and One simple solution would be, instead of having each angular modules for each components, declare a module and add the factory service to controllers as dependency.
Code:
var app = angular.module('myApp', []);
app.factory('FactoryService', ["$http", "$location", function($http, $location){
var my = this;
my.someFunction = function()
{
//communiate with backend and return data
}
return my;
}]);
app.controller('ControllerA', function($scope,$routeParams, FactoryService)
{
var my = this;
FactoryService.someFunction();
});
app.controller('ControllerB', function($scope,$routeParams, FactoryService)
{
var my = this;
FactoryService.someFunction();
});
Controllers are not injectable, because controller is not singleton. Controllers are constructor functions used to create instances of controllers. For example you can have multiple instances of one controller in your app:
angular.module('app', []);
angular
.module('app')
.controller('Example', function () {
this.x = Math.random();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="app">
First instance: <br>
<div ng-controller="Example as Ex1">
{{Ex1.x}}
</div>
Second instance: <br>
<div ng-controller="Example as Ex2">
{{Ex2.x}}
</div>
</div>
So if you want to share some behavior between controller you should use factory instead.
To inject a controller into another controller, use the $controller service.
app.controller('ControllerB', function($scope,$routeParams, $controller) {
var my = this;
$scope.ctrlA = $controller("ControllerA", {$scope: $scope});
});
The above example creates an instance of ControllerA as ctrlA with its $scope injected with the scope of the parent controller.
For more information, see AngularJS $controller Service API Reference.

AngularJS Base Controller load module

I have a baseController and a childController
Whenever I add modules to the baseController the app fails with the error:
Argument 'childController' is not a function, got undefined
EDIT: added a plnkr
http://plnkr.co/edit/mi9Ytv0HaqE47ENod4Gn
So this works:
angular
.module('app')
.controller('BaseController', baseController);
angular
.module('app', ['ui.grid', 'ui.grid.pagination'])
.controller('ChildController', childController)
childController.$inject = ['$controller'];
function childController($controller) {
var self = this;
var baseController = $controller('BaseController', {
$scope: self
});
But this below does not work: (note the add of the 'ui.bootstrap' in the baseController module section....)
angular
.module('app', ['ui.bootstrap'])
.controller('BaseController', baseController);
angular
.module('app', ['ui.grid', 'ui.grid.pagination'])
.controller('ChildController', childController)
childController.$inject = ['$controller'];
function childController($controller) {
var self = this;
var baseController = $controller('BaseController', {
$scope: self
});
You are defining the app module twice. I'm not clever enough to determine what's happening, but it should probably look like this instead:
angular
.module('app', ['ui.grid', 'ui.grid.pagination'])
.controller('BaseController', baseController)
.controller('ChildController', childController);
For inheritance you can use standard JavaScript inheritance patterns. Here is a demo which uses $injector.
function Parent($scope) {
$scope.name = 'Human';
$scope.clickParent = function() {
$scope.name = 'Clicked from base controller';
}
}
function Child($scope, $injector) {
$injector.invoke(Parent, this, {$scope: $scope});
$scope.name = 'Human Child';
$scope.clickChild = function(){
$scope.clickParent();
}
}
Child.prototype = Object.create(Parent.prototype);

How to use injected dependency in a angular service?

I am creating a custom service which logs a user in to my system. In this service, I need to use core services such as $http - How do I actually depend these to be used in my service?
My current code:
.factory('loginService', ['$http', '$rootScope', function() {
var login = function(){
console.log($http);
}
return {login : login};
}])
I call the login function from a controller like so
loginService.login();
I hoped that my console will output the $http object I injected, but it's returning undefined.
How do I access this in the correct way?
You need to add the dependencies to your function arguments:
.factory('loginService', ['$http', '$rootScope', function($http, $rootScope) {
//You can use $http and $rootScope here now
}
See the official docs for more info on Dependency Injection in angular
Services you inject need to be passed as arguments of the function:
['$http', '$rootScope', function($http, $rootScope)
By the way, you'll need to do the same where you're trying to use it:
app.controller(['loginService', function (loginService) {
loginService.login();
});
try this:
var myapp = angular.module('mainApp', []);
myapp.controller('myController', ['$scope', 'myFactory', function($scope, myFactory) {
myFactory.login();
}]);
myapp.factory('myFactory', ['$http', function($http) {
var services = {};
services.login = function() {
console.log($http);
}
return services;
}]);
View:
<div ng-app='mainApp' ng-controller='myController'></div>

How can I call a scope function inside a controller?

I am trying to call a scope function inside the controller. My aim is to call the function in the load itself.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.functionname();
$scope.functionname = function() {}
});
You can directly call the function in controller.
app.controller('customersCtrl', function($scope, $http) {
functionname();
function functionname {
//do something.
}
});
If you are looking to reuse the function outside controller then use Service as controllers are not injectable.
Read johnpapa style guide which shows best practices: https://github.com/johnpapa/angular-styleguide
app.controller('customersCtrl', function(someService) {
var vm = this;
activate();
function activate() {
// Do something.. You can get the data from your service
}
});
Then do your $http in services then inject it in your controller/s.
Best way is to use services:
var app = angular.module('myApp', []);
app.service('SomeService', ['$state', function ($state) {
this.someFunction = function() {
return "some value";
};
}]);
app.controller('customersCtrl', function($scope, $http, SomeService) {
SomeService.someFunction();
});

Resources