Angular JS: Inject service within app.js - angularjs

I want the users not to go to certain pages at least they've logged in before. I'm currently using this:
app.run(function ($rootScope, $route, $location)
{
var restrictedPages =
[
'/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
'/Auction/Detail', '/Survey/Accepted'
];
$rootScope.$on('$locationChangeStart', function (ev, next, current)
{
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if(restrictedPages.indexOf(nextPath) !== -1)
{
$location.path('/home');
}
});
});
My problem here is that I want to inject inside of this piece of code my AccountService. How can I achieve this? Because the loading-order is the following
app.js (the code presented is inside here)
homeService.js
accountService.js
I truly believe this is not the right way to go but it seems so simple and the only thing I'm missing is the account service injection.

Consider this module, which includes a accountService that uses implicit DI:
angular.module('myApp', [])
.factory('accountService', function($rootScope) {
// $rootScope is implicitly injected
})
.run(['$rootScope', '$route', '$location', 'accountService', function ($rootScope, $route, $location, accountService)
{
var restrictedPages =
[
'/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
'/Auction/Detail', '/Survey/Accepted'
];
$rootScope.$on('$locationChangeStart', function (ev, next, current)
{
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if(restrictedPages.indexOf(nextPath) !== -1 && !accountService.isLoggedIn())
{
$location.path('/home');
}
});
}]);
if you want more documentation: https://docs.angularjs.org/guide/di

Related

how to passing data from one controller to another controller using angular js 1

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
code Page1.html
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
now i want to show scope message into page2 controller
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
You can use $rootScope instead of $scope:
// do not forget to inject $rootScope as dependency
$rootScope.Message="Hi welcome";
But the best practice is using a service and share data and use it in any controller you want.
You should define a service and write getter/setter functions on this.
angular.module('app').service('msgService', function () {
var message;
this.setMsg = function (msg) {
message = msg;
};
this.getMsg = function () {
return message;
};
});
Now you should use the setMeg function in Controller1 and getMsg function in Controller2 after injecting the dependency like this.
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
$scope.Message="Hi welcome"
msgService.setMsg($scope.Message);
}]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
///here i want get that scope value
console.log('message from contoller 1 is : ', msgService.getMsg());
}]);
You should use services for it .
Services
app.factory('myService', function() {
var message= [];
return {
set: set,
get: get
}
function set(mes) {
message.push(mes)
}
function get() {
return message;
}
});
And in ctrl
ctrl1
$scope.message1= 'Hi';
myService.set($scope.message1);
ctrl2
var message = myService.get()
Sharing data from one controller to another using service
We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('Controller1', ['setGetData',function(setGetData) {
// To set the data from the one controller
$scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

How to inject factory to controller?

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.

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!

Calling a function from controller1 within controller2 in angularjs

I have a controller that updates my awards scope:
Controller 1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
})
}
}])
Controller 2
I have another controller 2 with a click event thats outside of this controllers scope. Is it possible for the controller below to call the $scope.updateAwardScope function from controller 1?
.controller('MainController', function ($rootScope, $scope) {
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});
I've found the use of the factory/service pattern to be a very effective way of reusing code in angular applications. For this particular case you could create an AwardFactory, inject it in your controllers and then call the update function. i.e
AwardFactory
myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
var factory = {
awards: []
};
factory.update = function() {
resource = TokenRestangular.all('award');
resource.getList().then(function (awards) {
factory.awards = awards;
});
return factory.awards; // You can skip the return if you'd like that
};
return factory;
}]);
YourController
.controller('MainController', function ($rootScope, $scope, AwardFactory) {
$scope.updateAwardScopeClick = function () {
AwardFactory.update();
}
});
Hope it helps!
You can use angular broadcast and receive
Controller1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
$rootScope.broadcast("update.awards");
})
}
}])
Controller 2
.controller('MainController', function ($rootScope, $scope) {
$rootScope.$on('update.awards', function(){
$scope.updateAwardScopeClick();
});
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});

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