bootstraping angular value provider - angularjs

My app.js, service.js, controller.js are declared as below. My problem is the controller only pickup the initial values {userId: -1, networkName: 'xyz'} set in the service.js, even though the values are changed to { userId: 129, networkName: 'mydomainaccoutname' } in myApp.run() block in the app.js. I have correctly injected the value provider to myApp.run() as well as the controller. How do I get the controller to pick up the updated values? Thanks.
app.js
(function () {
'use strict';
//debugger;
var myApp = angular.module('myApp', [
// Angular modules
'ngAnimate', // animations
//'ngRoute', // routing
'ngSanitize', // sanitizes html bindings (ex: sidebar.js)
'ui.router', // state routing
'ui.grid',
'ui.grid.pagination',
'ngResource', // RESTful resource
// Custom modules
'common', // common functions, logger, spinner
'common.bootstrap', // bootstrap dialog wrapper functions
// 3rd Party Modules
'ui.bootstrap' // ui-bootstrap (ex: carousel, pagination, dialog)
]);
myApp.run(['$templateCache', '$rootScope', '$state', '$stateParams', 'currentUserAccount', 'userFactory',
function ($templateCache, $rootScope, $state, $stateParams, currentUserAccount, userFactory) {
//currentUserAccount is a value provider service
currentUserAccount = { userId: 129, networkName: 'mydomainaccoutname' };
}]);
})();
service.js
'use strict';
angular.module('myApp')
.value('version', '5.0')
.value('currentUserAccount', {
userId: -1,
networkName: 'xyz'
});
controller.js
(function () {
'use strict';
//debugger;
var controllerId = 'shellCtrl';
angular.module('cmtApp').controller(controllerId,
['$rootScope', 'common', 'config', 'currentUserAccount', shell]);
function shell($rootScope, common, config, currentUserAccount) {
var vm = this;
var logSuccess = common.logger.getLogFn(controllerId, 'success');
var events = config.events;
vm.busyMessage = 'Please wait ...';
vm.isBusy = true;
vm.isAdmin = false;
vm.currentUser = currentUserAccount;
vm.spinnerOptions = {
radius: 40,
lines: 7,
length: 0,
width: 30,
speed: 1.7,
corners: 1.0,
trail: 100,
color: '#F58A00'
};
activate();
function activate() {
logSuccess('CMT loaded!', null, true);
common.activateController([], controllerId);
}
};
})();

Why not use a actual service instead? You can have your service like follows.
angular.module('app')
.service('UserService', [function() {
var currentUser = {
userId: -1,
networkName: 'xyz'
};
var getCurrentUser = function() {
return currentUser;
};
var setCurrentUser = function(user) {
currentUser = user;
};
// public functions
return {
getCurrentUser: getCurrentUser,
setCurrentUser: setCurrentUser
};
}]);
Then in your controller, you can do something like this:
(function () {
'use strict';
//debugger;
var controllerId = 'shellCtrl';
angular.module('cmtApp').controller(controllerId,
['$rootScope', 'common', 'config', 'UserService', shell]);
function shell($rootScope, common, config, UserService) {
var vm = this;
....
vm.currentUser = UserService.getCurrentUser();
...
};
})();
Then in your app runner:
myApp.run(['$templateCache', '$rootScope', '$state', '$stateParams', 'UserService', 'userFactory',
function ($templateCache, $rootScope, $state, $stateParams, currentUserAccount, userFactory) {
//currentUserAccount is a value provider service
UserService.setCurrentUser({ userId: 129, networkName: 'mydomainaccoutname' });
}]);

Related

angular module value not injected

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', []);

pass value from one different app module controller to another app module service using $rootScope in angularjs

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!

Angular-Jasmine injecting a service into the test

New to Jasmine, I am trying to instantiate my controller which has a list of dependencies (mainly the services I have written) and all the different ways I';ve tried haven't been right.
Here is my controller:
(function () {
'use strict';
angular.module('app.match')
.controller('MatchController', MatchController);
MatchController.$inject = ['APP_CONFIG', '$authUser', '$http', '$rootScope', '$state', '$stateParams', 'SearchService', 'ConfirmMatchService', 'MusicOpsService', 'ContentOpsService', 'MatchstickService', 'MatchService', 'Restangular'];
function MatchController(APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams, searchService, confirmMatchService, musicOpsService, contentOpsService, matchstickService, matchService, Restangular) {
var vm = this;
vm.greeting = '';
.
.
)();
Here is my test
(function(){
'use strict';
describe('app module', function() {
var MatchController;
//beforeEach(module('app.match'));
beforeEach(function($provide) {
module = angular.module('app.match');
$provide.service('SearchService', function(){
});
});
beforeEach(module('app.config'));
beforeEach(module('auth'));
beforeEach(inject(function($controller, APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams) {
MatchController = $controller('MatchController', {'APP_CONFIG':APP_CONFIG, '$authUser':$authUser, '$http':$http, '$rootScope':$rootScope, '$state':$state, '$stateParams':$stateParams, '$provide':$provide});
}));
describe("Match controller", function() {
it("should be created successfully", function() {
expect(MatchController).toBeDefined();
});
});
});
})();
Running test the above way gives me the following error:
TypeError: 'undefined' is not a function (evaluating '$provide.service('SearchService', function(){
})')
Try injecting the SearchService like this instead of using beforeEach.
describe('app module', function() {
var MatchController, SearchService;
beforeEach(module('app.match'));
beforeEach(module('app.config'));
beforeEach(module('auth'));
beforeEach(inject(function($controller, APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams, _SearchService_) {
SearchService = _SearchService_;
MatchController = $controller('MatchController', {
'APP_CONFIG':APP_CONFIG,
'$authUser':$authUser,
'$http':$http,
'$rootScope':$rootScope,
'$state':$state,
'$stateParams':$stateParams,
'$provide':$provide,
'SearchService': _SearchService_
});
}));
describe("Match controller", function() {
it("should be created successfully", function() {
expect(MatchController).toBeDefined();
});
});
});
})();
Similarly, you'll have to inject other services as well that your controller is relying on.

angularjs : issue with injecting $uibModalInstance

I have a controller :
(function() {
'use strict';
angular
.module('myApp')
.controller('ConsultantController', ConsultantController);
ConsultantController.$inject = ['$scope', '$state', 'Consultant'];
function ConsultantController ( $scope, $state, Consultant) {
var vm = this;
vm.consultants = [];
vm.loadAll = function() {
Consultant.query(function(result) {
vm.consultants = result;
});
};
vm.loadAll();
}
})();
If I inject the $uibModalInstance dependency:
(function() {
'use strict';
angular
.module('myApp')
.controller('ConsultantController', ConsultantController);
ConsultantController.$inject = ['$uibModalInstance','$scope', '$state', 'Consultant'];
function ConsultantController ( $uibModalInstance, $scope, $state, Consultant) {
var vm = this;
vm.consultants = [];
vm.loadAll = function() {
Consultant.query(function(result) {
vm.consultants = result;
});
};
vm.loadAll();
vm.clearSearchDialog = function() {
$uibModalInstance.dismiss('cancel');
};
}
})();
I am getting the following error :
angular.js:13294 Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- ConsultantController
http://errors.angularjs.org/1.5.2/$injector/unpr?p0=%24uibModalInstanceProvider%20%3C-%20%24uibModalInstance%20%3C-%20ConsultantController
at http://localhost:8181/bower_components/angular/angular.js:68:12
at http://localhost:8181/bower_components/angular/angular.js:4418:19
at Object.getService [as get] (http://localhost:8181/bower_components/angular/angular.js:4571:39)
at http://localhost:8181/bower_components/angular/angular.js:4423:45
at getService (http://localhost:8181/bower_components/angular/angular.js:4571:39)
at injectionArgs (http://localhost:8181/bower_components/angular/angular.js:4595:58)
at Object.instantiate (http://localhost:8181/bower_components/angular/angular.js:4637:18)
at $controller (http://localhost:8181/bower_components/angular/angular.js:9912:28)
at http://localhost:8181/bower_components/angular-ui-router/release/angular-ui-router.js:4081:28
at invokeLinkFn (http://localhost:8181/bower_components/angular/angular.js:9525:9) <div class="well ng-scope" ui-view="content">
But in my project there are several controllers with this dependency.
I don't understand why I have this error on this controller.
[UPDATE]
app.js :
(function() {
'use strict';
angular
.module('myApp', [
'ngStorage',
'ngResource',
'ngCookies',
'ngAria',
'ngCacheBuster',
'ngFileUpload',
'ui.bootstrap',
'ui.bootstrap.datetimepicker',
'ui.router',
'infinite-scroll',
'angular-loading-bar'
])
.run(run);
run.$inject = ['stateHandler'];
function run(stateHandler) {
stateHandler.initialize();
}
})();
working controller :
(function() {
'use strict';
angular
.module('myApp')
.controller('ConsultantDeleteController',ConsultantDeleteController);
ConsultantDeleteController.$inject = ['$uibModalInstance', 'entity', 'Consultant'];
function ConsultantDeleteController($uibModalInstance, entity, Consultant) {
var vm = this;
vm.consultant = entity;
vm.clear = function() {
$uibModalInstance.dismiss('cancel');
};
vm.confirmDelete = function (id) {
Consultant.delete({id: id},
function () {
$uibModalInstance.close(true);
});
};
}
})();
[UPDATE2 ]
.state('consultant.search', {
parent: 'consultant',
url: '/search',
data: {
authorities: ['ROLE_USER']
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/consultant/consultant-search-dialog.html',
controller: 'ConsultantController',
controllerAs: 'vm',
size: 'md',
}).result.then(function() {
$state.go('consultant', null, { reload: true });
}, function() {
$state.go('^');
});
}]
});

Angularjs error issue

I am getting an error TypeError: Cannot read property 'get' of undefined.i have tried so many ways but not able to solve.
mycode is login.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService'];
function LoginController($location, AuthenticationService, FlashService) {
var vm = this;
vm.login = login;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
function login() {
var usename=vm.username;
var password=vm.password;
vm.dataLoading = true;
$http.get('http://localhost:8080/ProjectManagement/REST/Login/Check?usename='+usename+'&password='+password+'').success(function(data, status, headers, config,response){
if (data=="0")
{
}
else
{
}
}).error(function(data, status, headers, config,response) {
});
};
}
})();
You missed to add $http dependency inside you controller, make sure all the dependencies are injected before using it.
Code
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService', '$http'];
function LoginController($location, AuthenticationService, FlashService, $http) {

Resources