What specific changes need to be made to the AngularJS code below to check for the existence of a cookie named myCookie every time a page is loaded, and then to set the $rootScope.myCookieValue variable to become the value of myCookie?
The code is from the sample app whose complete code you can explore at this link. It is a very simple example app, and I just want a simple working solution to this so that I can build up more complex approaches from it.
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).controller('navigation',
function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function() {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function($http) {
var self = this;
$http.get('resource/').then(function(response) {
self.greeting = response.data;
})
});
you can do it in run block I guess:
angular.module('hello', ['ngCookies', 'ngRoute'])
.config(function ($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'home',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).run(function ($rootScope, $cookies) {
var cookieValue = $cookies.get("myCookie");
if (cookieValue) {
$rootScope.myCookieVar = cookieValue;
}
}).controller('navigation',
function ($rootScope, $http, $location, $route) {
var self = this;
self.tab = function (route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function (response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function () {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function () {
$http.post('logout', {}).finally(function () {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function ($http) {
var self = this;
$http.get('resource/').then(function (response) {
self.greeting = response.data;
})
});
I think you should use angular version > 1.4.x
you should also add reference angular-cookies.js
Related
Here is my problem. Am new with angularjs and i want to get infos on the loggedin user. So i can for instance display it. I do not know how or where to start from here is my main angular controller.
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can anyone provide code please.
That is what a Service is for in Angular. Here is an example Authentication Service I am using in one of my Applications. If you want to keep a User logged in after closing the application you should also store the user in the local storage.
app.factory('AuthService', ['$q', '$http', 'LocalStorageService',
function($q, $http, LocalStorageService) {
var service = {};
service.user = LocalStorageService.get("AUTH_USER", null);
service.isLoggedIn = function(){
return service.user != null && service.user != undefined && service.user != "";
}
service.checkLogged = function(){
return $http.get(APPCONFIG.apiAccessPoint + "/user/" + service.user._id + "/isLogged").then(function(response){
if(!response.data.success || !response.data.logged){
service.logout();
return false;
}
else{
return true;
}
}, function(response){
service.logout();
return false;
});
}
service.login = function(name, password){
return $http.post(APPCONFIG.apiAccessPoint + "/user/login", {name: name, password: password}).then(function (response){
if(response.data.success){
LocalStorageService.set('AUTH_USER', response.data.data);
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data.token;
service.user = response.data.data;
}
return response.data;
}, function (response){
if(response.status == 400 || response.data.error_code == "VAL_ERROR"){
return response.data;
}
else{
return $q.reject();
}
});
}
service.logout = function(){
// remove token from local storage and clear http auth header
LocalStorageService.deleteValue("AUTH_USER");
$http.defaults.headers.common.Authorization = '';
service.user = null;
}
return service;
}]);
And this is how you would use the service in a controller (for example showing a profile):
app.controller('ProfileViewCtrl', ['$scope', '$routeParams', 'AuthService', 'UserService',
function($scope, $routeParams, AuthService, UserService) {
$scope.isLogged = AuthService.isLoggedIn();
$scope.user = null;
$scope.notFound = false;
$scope.ownProfile = false;
$scope.user = UserService.getUser($routeParams.user).then(function(response){
if(response.success){
$scope.user = response.data;
$scope.notFound = response.data == undefined;
if(!$scope.notFound && $scope.isLogged){
$scope.ownProfile = $scope.user._id == AuthService.user._id;
}
}
else{
console.log(response.data);
}
});
}]);
Or with the login page:
app.controller('LoginCtrl', ['$scope', '$route', 'AuthService',
function($scope, $route, AuthService) {
$scope.user = {};
$scope.login = function(){
AuthService.login($scope.user.name, $scope.user.password).then(function(response){
if(response.success){
$route.reload();
}
else{
console.log("Wrong User or password...");
}
});
}
}]);
I am having problem while injecting dependency from service to controller. Although i added it but still same error of
Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl
I basically need to render a ng-view to my index.html
Index.html
<div ng-view>
</div>
app.js
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'app/views/list.html', controller: 'listCtrl'
}).
otherwise({
redirectTo: '/list'
});
}]);
websiteService.js
app.factory('webiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
/* application services that would not return values */
app.service('websiteService', ['$http', function ($http) {
//service for pagination
this.paginate = function ($scope) {
//pagination code
$scope.currentPage = 1;
$scope.totalItems = $scope.model.length;
$scope.numPerPage = 10;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.model.indexOf(value);
return (begin <= index && index < end);
};
//ordering code
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}
//service to change state of a website
this.changeSiteState = function (website) {
var newState = website.State == "Stopped" ? "Started" : "Stopped";
$http({
method: 'POST',
url: '/Replicate/ChangeState/',
data: JSON.stringify({ webName: website.Name, state: newState }),
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
if (data == "success") {
website.State = website.State == "Stopped" ? "Started" : "Stopped";
}
else {
alert(data);
}
}).error(function (data, status, headers, config) {
alert(data);
});
}
}])
listCtrl.js
app.controller('listCtrl', function websiteCtrl($scope, $location, websiteFactory, websiteService, $modal) {
//function triggered at the intialization of controller
$scope.init = function () {
$scope.model = [];
setTimeout(function () {
websiteFactory.getAllWebsites().success(function (data) {
$scope.model = data;
websiteService.paginate($scope);
})
}, 0);
};
//delegation of change state to service method
$scope.changeState = function (website) {
websiteService.changeSiteState(website);
}
//open modal and shows details of single object
$scope.showDetails = function (websiteName) {
var modalInstance = $modal.open({
templateUrl: '../Views/Replicate/Details.html',
controller: 'DetailsCtrl',
resolve: {
obj: function () {
return websiteFactory.getFilteredObject($scope.model, websiteName);
}
}
});
}
});
You have misspelled "websiteFactory". In your factory definition code it is "webiteFactory" but in controller you are fetching it with different name using "websiteFactory" that's why it is not able to find this provider and producing error:
change:
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
That error comes when your factory is not registered with angular . Change it to
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
...do something here...
}
I want a simple HTML form showing user and password inputs, now form is showing up in modal box using bootstrap. I am good in java but my hands are tight on javascript and angularjs, bootstraps etc.
Code1
$scope.modalShown = false;
var showLoginDialog = function() {
if(!$scope.modalShown){
$scope.modalShown = true;
var modalInstance = $modal.open({
templateUrl : 'templates/login.html',
controller : "LoginCtrl",
backdrop : 'static',
});
modalInstance.result.then(function() {
$scope.modalShown = false;
});
}
};
other code from where the values are passing.
code2
.controller('LoginCtrl', [ '$scope', '$state', '$modalInstance' , '$window', 'Auth',
function($scope, $state, $modalInstance, $window, Auth ) {
$scope.credentials = {};
$scope.loginForm = {};
$scope.error = false;
//when the form is submitted
$scope.submit = function() {
$scope.submitted = true;
if (!$scope.loginForm.$invalid) {
$scope.login($scope.credentials);
} else {
$scope.error = true;
return;
}
};
//Performs the login function, by sending a requeora to the server with the Auth service
$scope.login = function(credentials) {
$scope.error = false;
Auth.login(credentials, function(user) {
//success function
$modalInstance.close();
$state.go('home');
}, function(err) {
console.log("error");
$scope.error = true;
});
code1 is written in the maincontroller of angular app where its triggering the modal box with user and password inputs getting credentials from login.js
I am trying to redirect users to a login page if they make an attempt to access pages that require them to be logged in. I am using Firebase and AngularJS, following this guide. The error explanation on the AngularJS site indicates that either a non-existent definition or duplicate definition is causing the issue but I cannot identify either of these in my code. Additionally, the stack trace of the error doesn't indicate which of my files caused the error, only mentioning the angular.js file.
Can anyone give me some insight as to what is causing this issue?
Note: The site runs without errors and users can log in and out if I leave out the resolve section of the $routeProvider.
Here is my app.js
angular.module('richWebApp', ['ngRoute', 'firebase', 'objectFilter'])
.constant('fb', {
url: 'https://<my-firebase-app>.firebaseio.com/' //name removed for security reasons
})
.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if(error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
})
.config(function($routeProvider){
$routeProvider.
when('/login', {
templateUrl: 'pages/login/login.html'
}).
when('/main', {
templateUrl: 'pages/main/main.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
when('/thread/:threadId', {
templateUrl: 'pages/thread/thread.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
otherwise({
redirectTo: '/login'
});
});
Here is the main.js controller
angular.module('richWebApp')
.controller('mainPageController', function($scope, $location, userService, currentAuth, threadService, fb, $firebaseAuth, $filter){
$scope.user = userService.getLoggedInUser();
$scope.newThreadTitle = '';
$scope.threadSubject = ''
$scope.createNewThread = false;
$scope.sortBy = 'dateAdded'
$scope.threads = threadService.getAllThreads();
$scope.getSubjects = function(subject) {
return $scope.threads.subject;
}
$scope.beginAddThread = function() {
$scope.createNewThread = true;
}
$scope.addThread = function(){
if(!$scope.newThreadTitle || !$scope.newThreadSubject){
return false;
}
var date = new Date();
var newThread = {
title: $scope.newThreadTitle,
subject: $scope.newThreadSubject,
username: $scope.user.name,
numComments: 0,
comments: [],
dateAdded: date.getTime()
};
$scope.threads.$add(newThread);
$scope.newThread = '';
$scope.newThreadTitle = '';
$scope.newThreadSubject = '';
$scope.createNewThread = false;
}
$scope.sortByDate = function() {
$scope.sortBy = 'dateAdded';
}
$scope.sortByPopularity = function() {
$scope.sortBy = 'numComments';
}
$scope.searchSubject = function(subject) {
$scope.searchThread = subject;
}
$scope.logout = function(){
userService.logout();
}
});
Here is the thread.js controller
angular.module('richWebApp')
.controller('threadPageController', function($scope, $location, $routeParams, $filter, currentAuth, threadService, fb, userService){
var threadId = $routeParams.threadId;
$scope.newComment = '';
var thread = threadService.getThread(threadId);
thread.$bindTo($scope, 'thread')
$scope.addComment= function(){
if(!$scope.newComment){
return false;
}
var currentUser = userService.getLoggedInUser();
var date = new Date();
var newComment = {
text: $scope.newComment,
username: currentUser.name,
dateAdded: date.getTime(),
userPic: currentUser.profilePic
};
$scope.thread.comments = $scope.thread.comments || [];
$scope.thread.comments.push(newComment);
$scope.thread.numComments += 1;
$scope.newComment = '';
}
});
Your code is referring to an Auth factory, which is shown in the example under Retrieving Authentication State. Include this in your code.
.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("<YOUR FIREBASE>");
return $firebaseAuth(ref);
}
]);
I have an angular controller called SubmissionTreeController and it has update_dashboard() function which refreshes the ui every minute.
My goal is to refresh the ui on successful post request from a different controller.
How do I make this function available in other controllers?
var module = angular.module("submissionDashboard", ['ui.tree', 'ngCookies', 'ui.bootstrap',]);
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal",
function($scope, $http, $modal) {
$scope.selected_items = {};
var update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
update_dashboard();
$scope.closeTask = function(scope) {
var modalInstance = $modal.open({
templateUrl: 'modal_close_submission_renderer.html',
controller: 'ModalCloseSubmissionController',
resolve: {
items: function () {
return $scope.selected_items;
}}
});
};
}]);
module.controller('ModalCloseSubmissionController', ['$scope', '$modalInstance', '$http', 'items', function ($scope, $modalInstance, $http, items) {
$scope.items = items;
$scope.selected = {
item: 1,
text: ''
};
$scope.ok = function () {
var val = $scope.selected.item;
if (val === 1) {
var url = Django.url('submission:close-notify', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 2) {
var url = Django.url('submission:close', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 3) {
var url = Django.url('submission:cancel', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
};
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
Edit:
What I am trying to do:
module.service('updateDashboardService', function($scope, $http){
this.update_dashboard = function() {
$scope = $scope;
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
});
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal", "updateDashboardService", function($scope, $http, $modal, updateDashboardService) {
$scope.selected_items = {};
updateDashboardService.update_dashboard();
var timer = setInterval(function() {
$scope.$apply(updateDashboardService.update_dashboard($scope, $http));
}, 1000 * 60);
What I am getting:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- updateDashboardService
Edit 2:
module.service('updateDashboardService', function($rootScope, $http){
this.update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$rootScope.list = data.results;
});
};
});
As #Gopesh says create a factory method, or, you can do something like this in SubmissionTreeController:
$scope.$on("event:updateDashboard", function(){ update_dashboard() });
And in your other controller:
$http.post(url, $scope.selected_items).success(function(data) {
$scope.$emit("event:updateDashboard");
});