calling public method from another js function inside service - javascript

I created custom service
(function () {
"use strict";
angular
.module("common.services")
.factory("redirectService",
["$q", "$location",
redirectService])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('redirectService');
});
function redirectService($q, $location){
...
var redirect = function() {
...
};
return {
doRedirect: redirect
};
}
inside my other controller where I'm injecting this redirectService I'm trying to call this publish doRedirect method
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController(redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}
Here I'm getting error on calling doRedirect method
Error: redirectService.doRedirect is not a function

You have an imbalance of number of arguments in dependency array and function arguments for MyController
Change
function MyController(redirectService){
To
function MyController($scope, redirectService){

MyController function has two arguments first $scope, second redirectService
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController($scope, redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}

Related

Ionic/Angularjs change controller to a global Variable

Here is my controller:
(function () {
var app= angular.module('app');
app.controller('recommendedJobsCtrl', ['$scope', function(dataShare,$q,$scope, $ionicSideMenuDelegate,$window,$http,$timeout) {
// passes contents to jobDetails to be rendered and displayed
window.post = function($event, res){
console.log(angular.element($event.target).parent());
dataShare.sendData(res)
}
/**
* handles pagination
*loads first 3 pages
**/
var i=1;
window.result=[];
window.noMoreItemsAvailable=false;
window.loadMore = function()
{
console.log('here')
if(i<4)
{
$http.get( "http://test.website.com/api/search/"+i).success(function(response)
{
i++;
$scope.result=$scope.result.push(response);
console.log(response);
$timeout(function ()
{
$scope.result = response
});
$scope.$broadcast('scroll.infiniteScrollComplete');
});
}else
{
$scope.noMoreItemsAvailable=true;
}
}
]);
}());
I read that my controller was under 'user strict' so it can't access the variables or functions. So I placed the word 'window' to make it global. But now it doesn't access the function because the console won't print. How do I fix this?
Dependency Injection is incorrect:
app.controller('recommendedJobsCtrl', [
'dataShare',
'$q',
'$scope',
'$ionicSideMenuDelegate',
'$window',
'$http',
'$timeout',
function(
dataShare,
$q,
$scope,
$ionicSideMenuDelegate,
$window,
$http,
$timeout) {
// Your code ...
}]);
Your code should be specific to the controller. You should create function and variables either on $scope as in $scope.<functionName> = function() {} and $scope.noMoreItemsAvailable or private to the controller as in function <functionName>() {} or var noMoreItemsAvailable.
In case intention behind using window object is to use same code across controllers, you may put this code in a factory.

AngularJS - I don't understand why factory is always undefined

I defined a factory that makes a get request but when I inject it in a controller it always throws an undefined error.
This is the factory:
(function() {
'use strict';
var app = angular
.module('myApp');
app.factory('homeFactory', homeFactory);
function homeFactory ($q, $http, $location) {
var data = {};
data.getProducts = getProducts;
function getProducts() {
return $http.get('http://localhost:8000/api/v1/products')
.error(errorMessage);
}
function errorMessage(response) {
console.log('There was an error', response);
}
return data;
}
})();
This is the controller:
(function() {
'use strict';
var app = angular
.module('myApp');
app.controller('homeController', homeController);
homeController.$inject =[homeFactory];
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
})();
It appears to be ok, but the console throws:
Uncaught ReferenceError: homeFactory is not defined
The problem is in your DI annotation. You should only use strings
homeController.$inject = ['homeFactory'];
See https://docs.angularjs.org/guide/di#-inject-property-annotation
The $inject property is an array of service names to inject.
The controller function supports dependency injection. You don't need to use the $injector directly. Try this:
var app = angular
.module('myApp');
app.controller('homeController', homeController);
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
The angular runtime will find the homeFactory service, and automatically pass it to your controller function when it's called.
In controller you shall put factory in dependecies
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);

Undefined variable passing data using service

I have declared my app and have one controller (for demonstration purposes):
var module = angular.module("app", [])
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
$scope.printEntity = function () {
console.log(dataService.getEntityArray());
}
}]);
And a service:
module.factory("dataService", function () {
var entityArrayService = [1,2];
return {
getEntityArray: function () {
return entityArrayService;
}
};
});
When I call $scope.printEntity from my view, I'm always told dataService.getEntityArray() is undefined.
I've loaded the service as a dependency and declared my entityArrayService array outside of my return statement. I've looked high and low for an answer but to no avail. My goal is to share a piece of data between two controllers, but at the minute I can't even use one controller to retrieve data.
The service isn't loaded as a dependency. Change this line:
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
to this:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
You are using strict syntax for dependencies declaration. So if you add a parameter to your controller, you must add its declaration too.
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
}
You didn't inject dataService in your controller. Try with:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
// ...
});
The injection of the service in the controller is missing:
please correct to:
...
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
The other code is correct.

myfunction() function call from one controller to another in angularjs

i have used Angularjs and i wanna call getcustomer function from one controller to another controller i have so many doing gooogling but i don't have an idea that how to call that
i have write below code which i used
var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function ($scope, $http) {
function getCutomers() {
$scope.loading = true;
$http.get('#Url.Content("~/Home/GetPesrons")').then(function (response) {
//var _data = angular.fromJson(response);
$scope.loading = false;
$scope.Customer = response.data; // please check the request response if list id in data object
}, function (error) {
throw error;
})
}
});
and second controller :
app.controller('MainCtrl', function ($scope, $http) {
getCutomers()
});
Mate, you will have to follow the following steps to resolve your problem. Firstly you have you create a factory
angular
.module('Napp')
.factory('CustomerFactory', ['$http', function ($http) {
var _factory = {};
_factory.getCustomers = function () {
return $http.get('#Url.Content("~/Home/GetPesrons")');
};
return _factory;
}]);
Then you can share data and functions between multiple controllers or services
GetAlphabetical Controller :
angular
.module('Napp')
.controller('GetAlphabetical', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
MainCtrl Controller :
angular
.module('Napp')
.controller('MainCtrl', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
This can be easily done by defining it as a service and injecting it as a dependency.
var app = angular.module('myApp', []);
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
app.controller('MainCtrl', function ($scope, $http, helloWorldFromService) {
app.controller('GetAlphabetical', function ($scope, $http, helloWorldFromService) {
Angular Service
What you want to do is to somehow communicate between two controllers. This can be easily be achieved using $broadcast & $on.
Incase there is a parent child relation between your controllers, use the following.
function firstCtrl($scope){
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope){
$scope.$on('someEvent', function(event, mass) {console.log(mass)});
}
If there is no parent child relationship between your controller, then inject $rootScope and broadcast using that.
related question - https://stackoverflow.com/a/14502755/1182982

Calling a Service function from a Controller in AngularJS

Controller Code
'use strict';
angular.module('MyApp').controller('ArticleContribEmailController', [
'$scope', 'ArticleAppState', 'fbsUserDataService', 'contribEmailService',
function ($scope, ArticleAppState, fbsUserDataService, contribEmailService ) {
this.userChanged = function () {
if (fbsUserDataService.initialized && fbsUserDataService.user && ArticleAppState.page_data) {
// user has authenticated.
contribEmailService.initForm();
}
};
// watch for when user data is available, run userChanged.
$scope.$watch(function() { return fbsUserDataService.user; }, this.userChanged);
$scope.$watch(function() { return fbsUserDataService.initialized; }, this.userChanged);
}
]);
Service Code
'use strict';
angular.module('forbesArticleApp').service('contribEmailService', [
'$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService',
function initForm ($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) {
console.log("Hello world!");
}
]);
I only want to fire the contribEmailService.initForm() function from the call in my controller, but it is firing as soon as the page loads.
How do I set when the service function initForm() is called?
Here is the corrected service code:
'use strict';
angular.module('forbesArticleApp').service('contribEmailService', [
'$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService',
function($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) {
return {
initForm: function() {
console.log("Hello world!");
}
};
]);
The service function is a factory that will in turn return the actual service. So it will run the first time it is requested as a dependency. The way you had it written, in fact, contribEmailService would have been undefined within your function, because your factory didn't actually return anything.
Hope this helps!
controller:-
blogcontroller is controller name
app.controller('blogController', function($scope, $compile, $http, blogAuth, AppInfo, $location,$element){
$scope.blog_abuse = function(blog_id)
{
blogAuth.BlogAbuse(blog_id).then(function(response)
{
$scope.DetailblogList.is_abused = response.records.is_abused;
},function(error){
});
}
});
service:-
app.factory('AppInfo', function(){
return {
serviceURL:site_url
};
});
app.service('blogAuth', function($http, $rootScope, $q, AppInfo){
this.BlogAbuse = function(blog_id){
var deferred = $q.defer();
var pageObj ={"blog_id":blog_id};
$http.post(AppInfo.serviceURL+'blog/blog_abuse',pageObj).success(function(data){
deferred.resolve(data);
}).error(function(msg, code) {
console.log('error', code, msg );
});
return deferred.promise;
}
});

Categories