I would like to store some information through module's function .value. I configure like follow
app:
angular.module('MyApp1', ['ngRoute', 'ngCookies', 'ngAnimate', 'angular-loading-bar' ])
angular.module('MyApp2', ['ngRoute', 'ngCookies', 'ngAnimate', 'angular-loading-bar'])
angular.module('MyApp3', ['ngRoute', 'ngCookies', 'ngAnimate', 'angular-loading-bar'])
.value('LoggedUser', {email: '',role: ''})
controller:
angular.module('MyApp1').controller('LoginController', ['LoggedUser', function ($scope, $cookies, $window, AuthenticationService, StorageService, SessionService, LoggedUser) { }]);
but I receive an error about injection module, which AuthenticationService, StorageService and SessionService are factory and correctly work.
Any suggestions?
UPDATE 1
Understood what #JB Nizet said. Modified like this:
angular.module('MyApp1', ['ngRoute', 'ngAnimate', 'angular-loading-bar'])
.value('LoggedUser', {
email: '',
role: ''
});
angular.module('MyApp2', ['ngRoute', 'ngAnimate', 'angular-loading-bar']);
angular.module('MyApp3', ['MyApp1', 'ngRoute', 'ngAnimate', 'angular-loading-bar'])
Is correct the dependencies? The life cycle must be:
in MyApp1 I insert some info in LoggedUser.
in MyApp3 I read from LoggedUser (from MyApp1)
MyApp2 is stand alone and it don't have any dependecies from MyApp1 and MyApp3.
UPDATE 2
This night I simplify the modules. Now I have only 2 modules. The modules are independent of each other
angular.module('MyApp1', ['ngRoute', 'ngAnimate', 'angular-loading-bar'])
angular.module('MyApp2', ['ngRoute', 'ngAnimate', 'angular-loading-bar'])
I create a factory for store global variables, this:
angular.module('MyApp2').factory('LoggedUserInformationService', function ($rootScope) {
var LoggedUser = {};
return {
Set: function (email, isAdmin) {
LoggedUser.Email = email;
LoggedUser.IsAdmin = isAdmin;
return LoggedUser;
},
Get: function () {
return LoggedUser;
}
};
//var LoggedUser = {};
//var loggedUserService = {};
//loggedUserService.Get = function () {
// return $rootScope;
//};
//loggedUserService.Set = function (email, battleTag, isAdmin) {
// User = {};
// User.Email = email;
// User.IsAdmin = isAdmin;
// $rootScope.$emit('LoggedUser', User);
//return loggedUserService;
}).run(function () { });
but when I Set data in a page, in other the get is undefined.
angular.module('MyApp2').controller("MenuController", function ($scope, LoggedUserInformationService) {
$scope.init = function () {
console.log(LoggedUserInformationService.Get());
}
});
Why is undefined?
You need to inject all dependencies in your controller.
angular.module('MyApp1').controller('LoginController',
['$scope', '$cookies', '$window', 'AuthenticationService', 'StorageService', 'SessionService', 'LoggedUser',
function ($scope, $cookies, $window, AuthenticationService, StorageService, SessionService, LoggedUser) {
// function def
}
]
);
or like this
angular.module('MyApp1').controller('LoginController', loginCtrl);
loginCtrl.$inject = ['$scope', '$cookies', '$window', 'AuthenticationService', 'StorageService', 'SessionService', 'LoggedUser'];
function loginCtrl($scope, $cookies, $window, AuthenticationService, StorageService, SessionService, LoggedUser){
//function def
}
count of dependencies that injected by inline annotation must be match count of parameters passing into function (implicit injected) .
Unknown provider: LoggedUserProvider <- LoggedUser <- LoginController
above error occurs because angular can't to recognize LoggedUser (that injected by inline annotation way) related to which parameters those are passing into function.
when using this type of annotation, take care to keep the annotation
array in sync with the parameters in the function declaration
angular.module('MyApp1', []);//set injections you need
angular.module('MyApp1').controller(
'LoginController'['$scope','$cookies','$window','AuthenticationService','StorageService','SessionService','LoginController', 'LoggedUser',
function ($scope, $cookies, $window, AuthenticationService, StorageService, SessionService, LoggedUser) {
//your code
});
furthermore you declare 3 modules those are separated and as JB Nizet and maher said you should have 3 sub-module and one main module and inject 3 module as sub modules of main module :
angular.module('MainApp', ['ngRoute', 'ngAnimate', 'angular-loading-bar','MyApp1','MyApp2','MyApp3']);
angular.module('MyApp1', []);
angular.module('MyApp2', []);
angular.module('MyApp3', []);
Related
Hi I am new to angularjs and I am trying to inject some factory to controller but I am facing difficulties. My factory works fine. I am able to set data in factory.
Below is my code where I inject factory.
function () {
angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, CONSTANTS, SomeFactory) {
var OTP = $stateParams.pageList.OTP;
$scope.EnterOTP = "Please enter this OTP to verify the user " + OTP;
//RegistrationOTPVerification.$inject = ['SomeFactory'];
//Facing issues in above line
alert(1);
function RegistrationOTPVerification(SomeFactory) {
var vm = this;
vm.someVariable = SomeFactory.getData();
console.log(vm.someVariable); // logs your data
alert(vm.someVariable);
}
});
This is my factory code.
(function () {
'use strict';
angular
.module('RoslpApp')
.factory('SomeFactory', SomeFactory);
SomeFactory.$inject = [];
function SomeFactory() {
var someData;
var factory = {
setData: setData,
getData: getData
};
function setData(data) {
someData = data;
}
function getData() {
return someData;
}
return factory;
}
})();
I set data in some other controller with SomeFactory.setData("123")
I want to inject someFactory as below:
RegistrationOTPVerification.$inject = ['SomeFactory'];
But whenever I write this, I get error RegistrationOTPVerification is undefined. If I comment that line everything works fine but I want to get some data from factory.
My factory name is SomeFactory and I want to inject in above controller. Any help would be appreciated.
Firstly, you missed CONSTANTS in your injections.
Next, I think you are mixing two kinds of syntax for controller here. Either use anonymous function or named. Don't mix both together.
Here's how your code should look like.
function () {
angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, SomeFactory) {
var vm = this;
var OTP = $stateParams.pageList.OTP;
vm.EnterOTP = "Please enter this OTP to verify the user " + OTP;
vm.someVariable = SomeFactory.getData();
console.log(vm.someVariable); // logs your data
alert(vm.someVariable);
});
You missed CONSTANTS in controller dependency list:
'$translate', '$state', '$stateParams', 'SomeFactory',
... $translate, $state, $stateParams, CONSTANTS, SomeFactory) {
So whatever you inject SomeFactory is available in controller under the name CONSTANTS and symbol SomeFactory is undefined.
I am doing project in angularjs,my requirement is need to pass value from one different app module controller to another app module service using $rootScope
Here my part of code
Login module and controller
var loginApp = angular.module('loginApp', [ 'ngCookies' ]);
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
$rootScope.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
});
here my app.js file
I injected the login module to another module
var smartCities = angular.module('smartCities', [ 'ngRoute', 'ngAnimate',
'ui.bootstrap', 'ngTouch', 'ui.grid.exporter', 'ui.grid',
'ui.grid.selection', 'ui.grid.autoResize', 'ngCookies', 'loginApp' ]);
below i access the loggedInuser here
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log($rootScope.loggedInUser);
$location.path(next.$$route.originalPath);
});
});
but in console i am getting message like
undifined
please tell me where i did wrong
you can use localstorage or sessionstorage for this purpose.
login Controller :
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
localStorage.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
loggedin user :
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(localStorage.loggedInUser);
$location.path(next.$$route.originalPath);
});
Here is the Doc Link: https://docs.angularjs.org/api/ng/type/angular.Module#value
//this is one module
var myUtilModule = angular.module("myUtilModule", []);
// this is value to be shared among modules, it can be any value
myUtilModule.value ("myValue" , "12345");
//this is another module
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
// myValue of first module is available here
}
myOtherModule.factory("myFactory", function(myValue) {
return "a value: " + myValue;
});
Hope It Helps!
Apologies for the code heavy post but I wanted to provide as much context as possible. I am having an issue with defining a service in my Angular.js application. Services are supposed to act as singletons throughout an application (source), so I am very confused to be getting the following behavior.
In my app.js file, I run my AmplitudeService Service and console.log(AmplitudeService). This outputs an object with all of the methods that I have defined within my AmplitudeService.js file. As such, I am able to properly use the service and log events as expected.
However, when I console.log(AmplitudeService) within my header.js, it outputs my Window object. As such, the Window does not contain functions such as "logEvent", "identifyUser", etc., so AmplitudeService is not usable in that case.
Would appreciate any and all insight!
AmplitudeService.js (source)
Note: If you check the author's syntax, he returns an object at the end of his service. In my research, I've read to use the "this" keyword when defining Service functions (source), and that you don't need to return an object as you would with a Factory, so I have updated it accordingly.
angular.module('AmplitudeService', [])
.service('AmplitudeService',
['$amplitude', '$rootScope', 'amplitudeApiKey', '$location',
function ($amplitude, $rootScope, amplitudeApiKey, $location) {
this.init = function() {
$amplitude.init(amplitudeApiKey, null);
$amplitude.logEvent('LAUNCHED_SITE', {page: $location.$$path});
}
this.identifyUser = function(userId, userProperties) {
$amplitude.setUserId(userId);
$amplitude.setUserProperties(userProperties);
}
this.logEvent = function(eventName, params) {
$amplitude.logEvent(eventName, params);
}
}]);
angular-amplitude.js (source)
This allows access to "$amplitude" throughout the application
(function(){
var module = angular.module('angular-amplitude', ['ng']);
module.provider('$amplitude', [function $amplitudeProvider() {
this.$get = ['$window', function($window) {
(function(e,t){
var r = e.amplitude || {};
var n = t.createElement("script");
n.type = "text/javascript";
n.async = true;
n.src = "https://d24n15hnbwhuhn.buttfront.net/libs/amplitude-2.2.0-min.gz.js";
var s = t.getElementsByTagName("script")[0];
s.parentNode.insertBefore(n,s);
r._q = [];
function a(e){
r[e] = function(){
r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));
}
}
var i = ["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];
for(var o = 0; o < i.length; o++){
a(i[o])
}
e.amplitude = r
}
)(window,document);
return $window.amplitude;
}];
}]);
return module;
}());
App.js
angular.module('app', [
'ngRoute',
'angular-amplitude',
'AmplitudeService',
])
.run(['AmplitudeService', function(AmplitudeService){
console.log(AmplitudeService); // Outputs 'Object {}'
AmplitudeService.init();
AmplitudeService.logEvent('LAUNCHED_SITE');
console.log(AmplitudeService); // Outputs 'Object {}'
}])
Header.js
angular.module('app.common.header', [])
.controller('HeaderCtrl', [ '$rootScope', '$scope', '$location', '$scope', '$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Window {}'
};
}]);
Looks like you are injecting $scope in your controller, causing the unexpected mapping of the variable
angular.module('app.common.header', [])
.controller('HeaderCtrl', [ '$rootScope', '$scope', '$location', **'$scope'**, '$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Window {}'
};
}]);
as an aside if find this format far easier to read / work with when defining controllers
angular
.module('app.common.header', [])
.controller('HeaderCtrl', headerController);
headerController.$inject = [ '$rootScope', '$scope', '$location', '$route', '$window', 'AmplitudeService']
function headerController($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Window {}'
};
}
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) {
I have ui.bootstrap as a dependency in my app, but I'm having an issue injecting the $modal service into my controller.
I'm getting the following error:
$modal is not defined
in my controller code, specifically in this function below where I attempt to open a modal :
function saveAndDisplayReport() {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
$location.url('index.html#/?reptname=' + vm.reptName);
}
Here's my reportmaint.js controller code header section, but Im' unclear on how to inject ui.bootstrap (please see the $modal parameter):
(function () {
'use strict';
var controllerId = 'reportmaint';
angular.module('app').controller(controllerId, ['$rootScope', '$scope', '$location', 'common', 'datacontext',
'gridHierarchyService', 'reportsContext', '$modal', reportmaint]);
function reportmaint($rootScope, $scope, $location, common, datacontext, gridHierarchyService, reportsContext) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var logErr = getLogFn("error");
...
})();
and here is my app.js where 'ui.bootstrap' is defined:
(function () {
'use strict';
var app = angular.module('app', [
// Angular modules
'ngAnimate', // animations
'ngRoute', // routing
'ngSanitize', // sanitizes html bindings (ex: sidebar.js)
// Custom modules
'common', // common functions, logger, spinner
'common.bootstrap', // bootstrap dialog wrapper functions
// 3rd Party Modules
'ui.bootstrap', // ui-bootstrap (ex: carousel, pagination, dialog)
'kendo.directives', // Kendo UI
'app.customcontrollers' // Language/Currency settings
//'ngjqxsettings' // jQWidgets init and directives (loaded in index.html)
]);
app.run(['$route', '$rootScope', 'common', 'userService', function ($route, $rootScope, common, userService) {
console.log("In app.run");
var getLogFn = common.logger.getLogFn;
var log = getLogFn('app');
}]);
})();
and in my index.html file I have the script reference :
<script src="scripts/ui-bootstrap-tpls-0.10.0.js"></script>
I am using this plunker as a live example, but I'm still going wrong somewhere - http://plnkr.co/edit/KsADLPaOfY7rtPTdWyYn?p=preview
thanks in advance for your help...
Bob
it seems like you are not injecting the modal at all ($modal is missing) in the function of your controller; try something like:
I'm not sure if reportmaint is a service, if not, just remove it
angular.module('app').controller('reportmaint', ['$rootScope', '$scope', '$location', 'common', 'datacontext','gridHierarchyService', 'reportsContext', '$modal', 'reportmaint',
function($rootScope, $scope, $location, common, datacontext, gridHierarchyService, reportsContext, $modal, reportmaint) {
//Client code
}
]);