i can't access to the cookies stored in localhost.
The cookis are already stored (view image)
When i try to display, i get undefined (view image)
Here is my js code for display :
var app = angular.module("Authentification", ['ngCookies']);
app.controller("log", ['$cookieStore', '$scope', '$http', function($cookieStore, $scope, $http) {
$scope.typeEmploye = $cookieStore.get('typeEmploye');
alert($scope.typeEmploye);
}]);
Here is my js code where i store the attribute in cookies after getting the result from my rest API.
var app = angular.module("Authentification", ['ngCookies']);
app.controller("main", ['$cookieStore', '$scope', '$http','$location',
function($cookieStore, $scope, $http, $location) {
$scope.user = [];
$scope.type=[];
$scope.auth = function() {
$http.get("/Employe/authentification?login=" + $scope.log + "&password=" + $scope.pw)
.success(function(data) {
console.log(data);
if (data) {
$scope.user = data;
$cookieStore.put('typeEmploye', $scope.user.type);
$cookieStore.put('Authentified',true);
$scope.type=$cookieStore.get('typeEmploye');
if($scope.type == "gerant"){
window.location.href = "/Gerant/index.html";
}
else if($scope.type == "cuisinier"){
window.location.href = "/Cuisinier/index.html";
}
else if($scope.type == "servant"){
window.location.href = "/Servant/index.html";
}
else{
window.location.href = "/error";
}
}
else{
alert("Login ou mot de passe incorrects");
}
}).error(function(data, status) {
alert("Problème dans le service d'authentification");
});
};
}]);
The information is stored in cookies. But, when i go to an other page ( with a different js file), i can't get the cookies. here is the js code.
var app = angular.module("ger", ['ngCookies']);
app.controller("main", ['$cookies', '$scope', '$http','$location',
function($cookies, $scope, $http, $location) {
var Type = $cookies.typeEmploye;
alert(Type);
}]);
Related
I'm using angularjs with Django.
Here is my angularjs script:
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope, $http){
$scope.name = 'sh';
$http.get('http://127.0.0.1:8000/json/ls/').then(function(response){
$scope.code = response.status;
$scope.text = response.statusText;
$scope.data = response.data;
},function(){
$scope.message = 'not found!';
});
});
And here's my http://127.0.0.1:8000/json/ls/ page's result:
{'record':[{'name':'your name','post':'dp'},{'name':'sdfsdfyour name','post':'sdfsfsfdp'},{'name':'your namefdsfsd','post':'dpsfdfsdf'},{'name':'your namesdfsdfs','post':'dpfsfdsfs'}]}
But $http.get('http://127.0.0.1:8000/json/ls') function showing me it's $scope.message's data as result. And you know that this result will be only shown while $http.get() will be failed to find the specific page. Have any suggestion/solution, please?
Hi I want to call a function after clicking on a button which is added to dom after angular is loaded. I dont know if this is possible in the way I am trying it, but I do know that my current code doesn't call the alert function.
After sending a search request to my backend, I get a list data entrys, which I display as hrefs.
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
results in
John Doe
Complete Code:
var appModule = angular.module('graph', [])
appModule.controller('graphCtrl', ['$scope', '$http', '$compile', function ($scope, $http, $compile) {
$scope.search = function () {
var data = {
}
$http.get('/api/search/?q=' + $scope.searchfield, data).success(function (data, status, headers, config) {
var result = data;
var searchResultsContainer = document.getElementById("dropdownId");
while (searchResultsContainer.firstChild) {
searchResultsContainer.removeChild(searchResultsContainer.firstChild);
}
for (i in result) {
var my_form = document.createElement("a");
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
my_text = document.createTextNode(result[i].caption)
my_form.appendChild(my_text)
searchResultsContainer.appendChild(my_form)
}
})
}
$scope.alert = function(){
alert("Hello! I am an alert box!!");
}
}
Hi I have created a factory to get the current amount of users online from my Firebase database.
When I first load the page it works great and displays all the current users but then if I go to another page and come back it will display as 0 until a new user connects or disconnects or if I refresh.
I followed this guide:
http://www.ng-newsletter.com/advent2013/#!/day/9
App.js
angular.module('myApp', ['ngRoute', 'firebase', 'ui.bootstrap'])
.factory('PresenceService', ['$rootScope',
function($rootScope) {
var onlineUsers = 0;
// Create our references
var listRef = new Firebase('https://my-db.firebaseio.com/presence/');
// This creates a unique reference for each user
var onlineUserRef = listRef.push();
var presenceRef = new Firebase('https://my-db.firebaseio.com/.info/connected');
// Add ourselves to presence list when online.
presenceRef.on('value', function(snap) {
if (snap.val()) {
onlineUserRef.set(true);
// Remove ourselves when we disconnect.
onlineUserRef.onDisconnect().remove();
}
});
// Get the user count and notify the application
listRef.on('value', function(snap) {
onlineUsers = snap.numChildren();
$rootScope.$broadcast('onOnlineUser');
});
var getOnlineUserCount = function() {
return onlineUsers;
}
return {
getOnlineUserCount: getOnlineUserCount
}
}
]);
mainController.js
angular.module('myApp')
.controller('mainController', function($scope, authService, PresenceService, $http, $routeParams, $firebaseObject, $firebaseAuth, $location) {
$scope.totalViewers = 0;
$scope.$on('onOnlineUser', function() {
$scope.$apply(function() {
$scope.totalViewers = PresenceService.getOnlineUserCount();
});
});
// login section and auth
var ref = new Firebase("https://my-db.firebaseio.com");
$scope.authObj = $firebaseAuth(ref);
var authData = $scope.authObj.$getAuth();
if (authData) {
console.log("Logged in as:", authData.uid);
$location.path( "/user/"+authData.uid );
} else {
console.log("Logged out");
$location.path( "/" );
}
// user ref
var userRef = new Firebase("https://my-db.firebaseio.com/users/"+ authData.uid);
var syncObject = $firebaseObject(userRef);
syncObject.$bindTo($scope, "data");
});
main.html
{{totalViewers}}
Inside your controller, change yr first line as below.
//$scope.totalViewers = 0;
$scope.totalViewers = PresenceService.getOnlineUserCount();
Because each time you leave the page, its controller gets flushed and next time its getting value "zero". So, correctly you should read $scope.totalViewers from your service.
I am relatively new to angular JS and I have an issue with angularJS 1.3.0 beta build
I am trying to insert my service (a standalone module) to a controller.
This is my app Code
'use strict';
angular.module('lifecareApp', [
'lifecareApp.validationServices'
, 'lifecareApp.loginController'
, 'lifecareApp.signupController'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/account/login', {
controller: 'loginController'
}).
when('/account/signup', {
controller: 'signupController'
})
$locationProvider.html5Mode(true);
});
This is my service code
'use strict';
angular.module('lifecareApp.validationServices', []).
factory('validationServices', function () {
return {
validateRequiredField: function (value, requiredMessage) {
if (value){
return false; //returns false
}else{
if (requiredMessage){
return requiredMessage;
}else{
return "Required";
}
}
},
validateEmail: function (value, required, requiredMessage, invalidEmailMessage){
//validate if its required first
if (required){
if (value){
//validate the email next
var checkEmailRegex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (checkEmailRegex.test(value)){
return false;
}else{
if (invalidEmailMessage){
return false;
}else{
return "Invalid Email";
}
}
}else{
if (requiredMessage){
return requiredMessage;
}else{
return "Required";
}
}
}
}
};
});
This is my controller code
'use strict';
/* Controllers */
angular.module('lifecareApp.loginController', []).
controller('loginController', ['$scope', 'validationServices' function ($scope, validationServices) {
$scope.emailError = false;
$scope.passwordError = false;
$scope.overallError = false;
$scope.login = function(){
var email = $scope.tbEmail;
var password = $scope.tbPassword;
var passwordValidation = validationServices.validateRequiredField(password);
var emailValidation = validationServices.validateEmail(email, true);
if (emailValidation){
$scope.emailError = true;
$scope.valEmail = emailValidation;
}else{
$scope.valEmail = "";
$scope.emailError = false;
}
if (passwordValidation){
$scope.passwordError = true;
$scope.valPassword = passwordValidation;
}else{
$scope.valPassword = "";
$scope.passwordError = false;
}
if (passwordValidation || emailValidation){
$scope.overallError = true;
$scope.valError = "Login Error!";
return;
}else{
$scope.overallError = true;
$scope.valError = "";
}
};
}]);
And I keep getting this error.
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0-beta.5/$injector/modulerr?p0=lifecareApp&…ngularjs.org%2F1.3.0-beta.5%2F%24injector%2Funpr%3Fp0%3D%2524routeProvider......5)
Please help! =(
I also found out that angular 1.0.7 does not have this error whereas the lastest angular 1.2.16 and 1.3.0 has this error.
In your main module you need to include ngRoute dependency with the new version of angularjs
angular.module('lifecareApp',['ngRoute',....
Also remember to include the route script file
<script src="angular-route.js">
I have two views right now.
login
main
Right now I login and change my path to /main which works fine. When I am not logged in, and try to visit /main my web service returns "Access denied for user anonymous" which I then forward them to / which is my login view. How can I pass something so my LoginController knows they were forwarded from /main to alert them to login first?
LoginController.js
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
$scope.email = "";
$scope.password = "";
$scope.fetching = false;
$scope.error = null;
$scope.login = function()
{
$scope.error = null;
$scope.fetching = true;
LoginModel.login($scope.email, $scope.password);
}
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
$location.path('/main');
}
else
{
$scope.error = args.result;
}
});
});
MainController.js
VforumJS.controller('MainController', function($scope, $location, $routeParams, MainModel)
{
$scope.currentTitle = '-1';
$scope.presentationData = MainModel.getPresentations();
$scope.$on('PresentationsLoaded', function(event, args)
{
log(args.result);
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.path("/");
}
});
});
You can use $location.search() in your MainController to pass query string to the LoginController.
Inside you MainController:
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.search({ redirectFrom: $location.path() });
$location.path("/");
}
And then in your LoginController, shortened for brevity:
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
var queryString = $location.search();
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
if (queryString && queryString.redirectFrom) {
$location.path(queryString.redirectFrom);
} else {
$location.path('/somedefaultlocation');
}
}
else
{
$scope.error = args.result;
}
});
});
Alternatively you can use a shared service, maybe even your LoginModel to set a parameter from MainController to indicate the redirect came from it.
Update
Even better still, use $httpProvider.interceptors to register a response interceptor, and then use the same $location.search() technique described above to redirect to the login screen on authentication failure. This method is ideal as your controllers are then clean of authentication logic.
$location broadcasts $locationChangeStart and $locationChangeSuccess events, and the third param of each is oldUrl.
One solution would be to have a service that subscribes to $locationChangeStart in order to save the current and old urls.
When you hit /, your LoginController can check your service to see if the oldUrl is /main, and then act accordingly.