Working with multiple factories in angular - angularjs

I was working with only 1 factory in angular, but now that my project has grown too large, I want to split the file in separate factories.
My factories are like this:
angular.module('factories')
.factory('auth', ['$http', '$state', '$window',
function($http, $state, $window) {
var auth = {};
......
return auth;
Userfactory:
angular.module('factories')
.factory('userFactory', ['$http', '$state', '$window',
function($http, $state, $window) {
var userFactory = {};
return userFactory;
I inject them in my controllers:
angular.module('controllers')
.controller('UserCtrl', ['$scope', '$state', 'auth', 'userFactory', 'Facebook',
function ($scope, $state, auth, userFactory, Facebook) {
However I get the following error:
Error: [$injector:unpr]
http://errors.angularjs.org/1.4.7/$injector/unpr?p0=userFactoryProvider%20%3C-%20userFactory%20%3C-%20UserCtrl
I'm also bootstrapping my factories:
angular.module('factories', []);
And I inject factories into app.js:
var app = angular.module('eva', ['ui.router', 'ngMaterial', 'ngMessages',
'controllers', 'factories', 'ngAnimate', '720kb.socialshare',
'angular-loading-bar', 'angular-svg-round-progress', 'pascalprecht.translate',
'facebook']);
What is the proper way to work with multiple factories?

Check if you imported the script into your index file. You need files from both of services to be imported after the angular.js file.

Since factories are in a separate module so you need to set dependency for controller module because it is using factories from factories module.
Do something like
angular.module('controllers', ['factories'])
.controller('UserCtrl', ['$scope', '$state', 'auth', 'userFactory', 'Facebook',
function ($scope, $state, auth, userFactory, Facebook) {

Related

Angular js factory injection

I am new to Angular JS. I have created factory as follows.
angular.module('login',[])
.factory('authFactory',[function(){
// logic
}] );
and have injected into controller, but it gives me an error.
I also provided this factory file in index.html, but the error is the same.
[$injector:unpr] Unknown provider: authFactoryProvider <- authFactory
What should I do to avoid this?
Below is the code where I have injected it.
(function () {
'use strict';
angular.module('login', []).controller("LoginController", loginController)
loginController.$inject = ['$cookies', '$log', '$scope', '$rootScope', '$q', '$location', '$timeout', '$window',authFactory];
function loginController($cookies, $log, $scope, $rootScope, $q, $location, $timeout, $window,authFactory) {
Did you mean this? (you are missing '')
loginController.$inject = ['$cookies', '$log', '$scope',
'$rootScope', '$q', '$location', '$timeout', '$window', 'authFactory'];
Don't create module twice:
angular.module('login', [])
.factory('authFactory',[function(){
// logic
}] )
angular.module('login').controller("LoginController", loginController)
Don't use module twice make it as your practice to code like this
(function () {
'use strict';
var login = angular.module('login',[]);
login.factory('authFactory',[function(){
// logic
return {
}
}]);
login.controller("LoginController", loginController);
loginController.$inject = ['$log', '$scope', '$rootScope', '$q', '$location', '$timeout', '$window','authFactory'];
function loginController($log, $scope, $rootScope, $q, $location, $timeout, $window,authFactory) {
}
})();
As you are new to angular, i would recommend you to go through this youtube video which is very good
https://www.youtube.com/watch?v=FDhGmFul4YU&index=2&list=PLvZkOAgBYrsS_ugyamsNpCgLSmtIXZGiz

angular injector error with config()

I want to inject a config into my angular app. The app contains also an run object.
But when I add the config option I get an $injector:modulerr error. And I can't find the error.
var myApp = angular.module('myApp',[
'ngAnimate',
'ui.bootstrap',
'ui.router',
'angular.filter',
'angularUtils.directives.dirPagination',
'validation.match',
'ngSanitize',
'ngCookies',
'pascalprecht.translate',
'toggle-switch',
'angucomplete-alt',
'cgPrompt',
'dndLists',
'ngFileUpload',
'ui.router.breadcrumbs',
'angular-bind-html-compile',
'rzModule', // range slider (i.e. for price filter)
'ngFileSaver',
'angular-input-stars',
'textAngular',
'textAngular-uploadImage'
]);
myApp.config(function($provide) {
$provide.decorator('taOptions', function($delegate) {
$delegate.toolbar[1].push('uploadImage');
return $delegate;
});
});
myApp.run(['$rootScope', '$window', '$location', '$stateParams', '$api', '$translate', '$transitions', '$state',
function($rootScope, $window, $location, $stateParams, $api, $translate, $transitions, $state) {
//rootscope
}]);
It's going about the textAngular-uploadImage module (https://github.com/mrded/textAngular-uploadImage). When I remove the config option my app runs fine, but of course, I can't use the module.
What is the reason for this? I included al the required files in the html, and textAngular (https://github.com/textAngular/textAngular) is working fine.
How can I solve this? Or are there any other options for a normal upload function in textAngular? I also tried this solution (https://github.com/textAngular/textAngular/issues/139#issuecomment-111205679) but I get the same error.
Try something below code..
myapp.config(['$provide', function($provide){
$provide.decorator('taOptions', ['$delegate', function(taOptions){
taOptions.toolbar[1].push('uploadImage');
}
return taOptions;
}];
});
And you would need to register upload image with editor like below
taRegisterTool('uploadImage', {
iconclass: "fa fa-user",
action: function(){
//code
}
});

Can I have two angular.module calls to the same ng-app in two different files for same controller?

Hi I have created two angulerjs files for same ng-app example.
admin.js
var app = angular.module('arcadminmodule', ['ngTable', 'ui-notification']);
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
admin1.js
var app = angular.module('arcadminmodule');
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
But its overriding admin.js from admin1.js
please help me out....
In admin1.js when you write:
var app = angular.module('arcadminmodule');
you are not creating a new module. You are trying to get an existing module named 'arcadminmodule'.. If you want to create a new module, you will have to write something like this:
var app = angular.module('arcadminmodule',[]); // add your depencencies...
Now, In your case, in admin.js you are creating your module and admin1,js you are making use of the same module. In angular you cannot have two controllers with the same name. Controllers are for (from the docs):
Set up the initial state of the $scope object.
Add behavior to the $scope object.
So If you need are trying to apply some roles or some business logic, It need to go into one controller. Make sure your controller contain only the business logic needed for a single view.
I think its no need for use the same controller in two places.But you can use services in places.If you need to do some think different from the ArcAdminController,use this structure.
Services
-service1.js
(function (angular) {
angular.module('marineControllers').service('boatService', function (ajaxService) {
}
)
-service2.js
-module..js
var artistControllers = angular.module('marineControllers',['ngAnimate']);
Controllers
-controller1
(function (angular) {
angular.module('marineControllers').controller("BoatController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'boatService', 'autocompleteFactory', 'utilityFactory',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, boatService, autocompleteFactory, utilityFactory) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
-controller2
(function (angular) {
angular.module('marineControllers').controller("DeviceController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'deviceService', 'autocompleteFactory', 'utilityFactory','commonDataService',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, deviceService, autocompleteFactory, utilityFactory,commonDataService) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
I have been use many services in both controllers,still they are different logics.

Angularjs - injecting dependencies into multiple controllers

I'm still quite new to angular, and have been building a simple CRM application. For a single resource (restful API resource) I have 3-4 routes and controllers defined in my angular application. Now, there are a set of services and modules that I repeatedly have to inject into each controller. I understand that each controller will have it's own instance of scope and shared instance of factory/services but is there a way to centrally define dependencies for multiple controllers?
In the example below, $modal, growl, configuration, $scope are injected into all 3 controllers, I'd like to define that only once.
Listings Controller
myApp.controller('VenueListCtrl', ['$scope', '$http', 'configuration', '$modal', 'growl',
function ($scope, $http, configuration, $modal, growl) {
}
]);
Create/New Controller
myApp.controller('VenueCreateCtrl', ['$scope', '$http', '$location', 'configuration',
function ($scope, $http, $location, configuration) {
}
]);
Details Controller
myApp.controller('VenueDetailCtrl', ['$scope', '$routeParams', '$http', '$modal', 'configuration',
function ($scope, $routeParams, $http, $modal, configuration) {
}
]);
Best you can do is: use not-anonymous function declaration of controllers:
var depsToInject = ['$scope', 'growl', 'configuration', '$modal'];
myApp.controller('Ctrl1' , Ctrl1);
Ctrl1.$inject = depsToInject ;
function Ctrl1($scope, growl, configuration, $modal) {
// ...
}
myApp.controller('Ctrl2' , Ctrl2);
Ctrl2.$inject = depsToInject ;
function Ctrl1($scope, growl, configuration, $modal) {
// ...
}
etc. But that does not fully unify declaration and I don't think there is a better way. However you can try from the other side and wrap your dependencies with another dependency, but I don't like this way either.

Angularjs Error: [ng:areq] http://errors.angularjs.org/1.2.8/ng/areq?p0=fn&p1=not%20aNaNunction%2C%20got%string

I'm new to angularjs and I'm working on a single page-app. I'm getting this error message that doesnt tell me where in my code that's throwing this error and I've went on angularjs' website to look up the error but I dont understand it.
This is the error message I'm getting,
Error: [ng:areq] http://errors.angularjs.org/1.2.8/ng/areq?p0=fn&p1=not%20aNaNunction%2C%20got%string
Any ideas on what might be throwing this error? Thanks
Edit: The error might have something to do with the way I declare my modules but I still can't figure it out. Here's a sippet of my code ...
var user = angular.module('user', ['ui.bootstrap','ngResource']);
user.controller("user", ["$scope", "$resource", "$location", '$state',
function($scope, $resource, $location, $state) { }]);
var saveObject = angular.module('saveObject', ['ui.bootstrap','ngResource'])
.factory('savedObject', function($resource) {});
var saveUser = angular.module('saveUser', ['saveObject']);
saveUser.service('saveUser', 'savedObject', function(savedObject) {});
var route = angular.module('route', ["ui.router", 'ngResource', 'saveUser'])
route.config(function($stateProvider, $urlRouterProvider, $locationProvider) {});
route.controller('add_userController', ["$scope", "$resource", '$state', '$timeout', '$rootScope', '$http', 'saveUser',
function($scope, $resource, $state, $timeout, $rootScope, $http, saveUser) {}]);
route.controller('add_familyController', ["$scope", "$resource", '$state', '$timeout', '$rootScope', '$http', '$window', 'saveUser',
function($scope, $resource, $state, $timeout, $rootScope, $http, $window, saveUser) {}]);
Your service definition seems to be messed up:
var saveUser = angular.module('saveUser', ['saveObject']);
saveUser.service('saveUser', 'savedObject', function(savedObject) {});
should be maybe
var saveUser = angular.module('saveUser', ['saveObject']);
saveUser.service('saveUser', ['savedObject', function(savedObject) {}]);

Resources