Token-Based Authentication With AngularJS & NodeJS - javascript

So, I came up from this Token-Based Authentication With AngularJS & NodeJS tutorial.
Now I want to implement my own RESTful Api to my AngularJS. Here it is my RESTful Api: http://amr2.mybluemix.net/getpop/list
The response from JSON is like this:
[
{
"_id": "fe107409a330778c0e22ebd8e34ca8fd",
"_rev": "2-292360cf343367741469397112ff9a82",
"d": {
"parentsite": "1",
"siteID": "10001",
"location": "",
"domain": "#test",
"users": {
"0": {
"user": "admin#test",
"pass": "12345",
"level": 0
},
"1": {
"user": "view#test",
"pass": "12345",
"level": 1
}
},
"readpoint": {
"0": {
"uSN": "100010001",
"metername": "demokit",
"activedate": ""
},
"1": {
"uSN": "100010002",
"metername": "demokit2",
"activedate": ""
}
}
}
}
]
I want to authenticate whether it is admin#test or view#test whose login to my angular.
This is <body> in my index.html
<body ng-app="angularRestfulAuth">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" data-ng-controller="HomeCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular Restful Auth</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a ng-href="#/">Home</a></li>
<li data-ng-show="token"><a ng-href="#/me">Me</a></li>
<li data-ng-hide="token"><a ng-href="#/signin">Signin</a></li>
<li data-ng-hide="token"><a ng-href="#/signup">Signup</a></li>
<li data-ng-show="token"><a ng-click="logout()">Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" ng-view="">
</div> <!-- /container -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>
<script src="/lib/ngStorage.js"></script>
<script src="/lib/loading-bar.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers.js"></script>
<script src="/scripts/services.js"></script>
</body>
This is services.js
'use strict';
angular.module('angularRestfulAuth')
.factory('Main', ['$http', '$localStorage', function($http, $localStorage){
var baseUrl = "https://amr2.mybluemix.net/getpop/list";
function changeUser(user) {
angular.extend(currentUser, user);
}
function urlBase64Decode(str) {
var output = str.replace('-', '+').replace('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
return window.atob(output);
}
function getUserFromToken() {
var token = $localStorage.token;
var user = {};
if (typeof token !== 'undefined') {
var encoded = token.split('.')[1];
user = JSON.parse(urlBase64Decode(encoded));
}
return user;
}
var currentUser = getUserFromToken();
return {
save: function(data, success, error) {
$http.post(baseUrl + '/signin', data).success(success).error(error)
},
signin: function(data, success, error) {
$http.post(baseUrl + '/authenticate', data).success(success).error(error)
},
me: function(success, error) {
$http.get(baseUrl + '/me').success(success).error(error)
},
logout: function(success) {
changeUser({});
delete $localStorage.token;
success();
}
};
}
]);
This is controller.js
'use strict';
angular.module('angularRestfulAuth')
.controller('HomeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main', function($rootScope, $scope, $location, $localStorage, Main) {
$scope.signin = function() {
var formData = {
email: $scope.email,
password: $scope.password
}
Main.signin(formData, function(res) {
if (res.type == false) {
alert(res.data)
} else {
$localStorage.token = res.data.token;
window.location = "/";
}
}, function() {
$rootScope.error = 'Failed to signin';
})
};
$scope.signup = function() {
var formData = {
email: $scope.email,
password: $scope.password
}
Main.save(formData, function(res) {
if (res.type == false) {
alert(res.data)
} else {
$localStorage.token = res.data.token;
window.location = "/"
}
}, function() {
$rootScope.error = 'Failed to signup';
})
};
$scope.me = function() {
Main.me(function(res) {
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
})
};
$scope.logout = function() {
Main.logout(function() {
window.location = "/"
}, function() {
alert("Failed to logout!");
});
};
$scope.token = $localStorage.token;
}])
.controller('MeCtrl', ['$rootScope', '$scope', '$location', 'Main', function($rootScope, $scope, $location, Main) {
Main.me(function(res) {
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
})
}]);
This is app.js
'use strict';
angular.module('angularRestfulAuth', [
'ngStorage',
'ngRoute',
'angular-loading-bar'
])
.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/signin', {
templateUrl: 'partials/signin.html',
controller: 'HomeCtrl'
}).
when('/signup', {
templateUrl: 'partials/signup.html',
controller: 'HomeCtrl'
}).
when('/me', {
templateUrl: 'partials/me.html',
controller: 'HomeCtrl'
}).
otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);
}
]);
Can anybody show me what i have been missing and how to fix it?

Related

How do I populate html using angular controller prior to display

I am trying to pre-load data based on ng-controller attributes prior to displaying the html and in turn prior to button click(submit). I am new to angular js and not sure how to accomplish the task.
There will be one question and n number of answer options
May last try is as seen in code but I need to get to the controller other than button click. I need to see the question and possible answers before the html is present.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/angularjs.min.1.7.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-route.min.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/app.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/vote.js"></script>
<!--<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/HomePageVoteController.js"></script>-->
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/vote.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/route.js"></script>
<script>
// app
var app = angular.module('quickSurveyApp', ["ngRoute"]);
// controller(s)
app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
//app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
// app.factory("VoteService", ["$scope", "qa", "$location", function ($scope, qa, $location) {
$scope.activeQuestions = qa.activeQuestions;
$scope.records = qa.records;
$scope.QuestionText = qa[0].QuestionText;
$scope.AnswerText = qa[0].AnswerText;
$scope.Answers = qa[0].Answers;
$scope.error = false;
$scope.AddVote = function () {
$scope.error = !!$scope.answer;
}
}]);
// service(s)
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
res.setHeader('Access-Control-Allow-Origin', '*');
var service = {};
//Gets all data for page.
var questionNumber = 0;
service.pageInit = function () {
var deferred = $q.defer();
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);
// route(s)
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick Survey/survey.html",
//controller: "VoteCtrl",
controller: "VoteCtrl",
// it's is good to download the data before displaying the template without the data
// so all we found in resolve is gonna be "resolved" before display the page and running the controller
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
return VoteService.pageInit();
}]
}
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
<body ng-app="quickSurveyApp">
<div>
<h1>Quick Survey</h1>
<div ng-view></div>
</div>
</body>
</html>
var app = angular.module("quickSurveyApp", ["ng-Route"]);
app.config(["$routeProvider", function ($routeProvider) {
//res.setHeader('Access-Control-Allow-Origin', '*');
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick-Survey/survey.html",
//templateUrl: "/API/quick-survey/api-test-pages/Quick Survey/survey.html",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
// return VoteService.pageInit(1);
return VoteService.pageInit();
}]
}
})
.when("/question/:q", {
templateUrl: "templates/survey.tpl",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
var questionNumberFromURL = $route.current.params.q;
//return VoteService.pageInit(questionNumberFromURL);
return VoteService.pageInit();
}]
}
})
.when("/thanks", {
templateUrl: "templates/home.tpl",
controller: ["$timeout", "$scope", "$location", function ($timeout, $scope, $location) {
$scope.message = "Thank you !!!";
$timeout(function () {
$location.path("/");
}, 3000);
}]
}).
otherwise({
redirectTo: '/xxxx.html'
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Timothy+Mruk&id=13332&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
app.controller("VoteCtrl", function ($scope, $http) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
//Gets all data for page.
$scope.pageInit = function () {
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsbyZone/0'
//*url: 'http://localhost:51230/api/Question/GetQuestionsByZone/0'
}).then(function (response){
$scope.activeQuestions = response.data;
},function (error){
console.log(error);
});
};
// inserts new request
$scope.insertRequest = function () {
$http.post("/API/quick-survey/api/Vote/AddVote", $scope.voteRequest).then(function (data, status, headers, config) {
alert("success");
}, function (data, status, headers, config) {
console.log("error!");
console.log(data);
});
};
// checks if user already voted for a question
$scope.getUserVoteCount = function () {
// get true or false
$http.get("/API/quick-survey/api/Vote/GetUserVoteCount/866/ijohnson/0").success(function (data, status, headers, config) {
$scope.activeQuestions = data;
}).error(function (data, status, headers, config) {
console.log(status);
});
};
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
app.controller("VoteCtrl", ["$scope","qa","$location", function ($scope, qa, $location) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
$scope.activeQuestions = qa.activeQuestions;
//*******
$scope.Answers = qa.records;
$scope.error = false;
$scope.AddVote = function () {
if ($scope.answer == undefined)
$scope.error = true;
else {
$scope.error = false;
if (qa.next)
$location.path("question/" + qa.next)
else
$location.path("thanks");
}
}
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=22665&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
}]);
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
var service = {};
var urlBase = "API/quick-survey/api";
$scope.pageInit = function () {
// Get Questions from api
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsByZone/0'
}).then(function (response) {
$scope.activeQuestions = response.data;
}, function (error) {
console.log(error);
});
};
//Gets all data for page.
service.pageInit = function () {
var deferred = $q.defer();
//res.setHeader('Access-Control-Allow-Origin', '*');
//$http.get(urlBase + '/Question/GetQuestionsByZone/' + questionNumber).then(function (response) {
// $http.get(urlBase + '/Question/GetQuestionsByZone/' + 0).then(function (response) {
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// inserts new request
service.insertRequest = function (questionNumber) {
var deferred = $q.defer();
$http.post(urlBase + '/Vote/AddVote', $scope.voteRequest).then(function (response, status, headers, config) {
console.log(response.data);
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// checks if user already voted for a question
service.getUserVoteCount = function (questionNumber) {
var deferred = $q.defer();
// get true or false
$http.get(urlBase + '/Vote/GetUserVoteCount/866/ijohnson/' + questionNumber).success(function (response, status, headers, config) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);// JavaScript source code
h1>Quick Survey</h1>
<div ng-model="QuestionText">
<!--Question-->
<h2>{{QuestionText}}</h2>
</div>
<!-- <div -->
<div ng-model="AnswerText">
<!--Possible Answers-->
<br ng-repeat-start="a in Answers" />
<input id="button{{a.AnswerText}}" name="selection" value="{{a.AnswerText}}" type="radio" ng-model="$parent.Answer" />
<label for="button{{a.AnswerText}}" ng-repeat-end>{{a.AnswerText}}</label>
</div>
<br />
<br />
<div>
<input id="surveybtn" type="button" value="Vote Now" ng-click="AddVote()" />
</div>

Ionic google maps not loading view with firebase authentication

My ionic 1 project currently has firebase authentication which lets the user log in with an email and password and redirects the user to view that can only be accessed when the user is logged in.
I want to load google maps on the logged in view. I have successfully been able to load google maps on another view that does not firebase authentication in its controller but the minute I put the same code in the controller of the logged in view and setup the div with on the logged in view then it does not load up. There have been no errors in console so im not quite sure what is going on.
So code is as followed:
AuthService calls the firebase service
MuserController (Controller of logged in view):
.controller('MuserCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, ionicMaterialMotion, $state, AuthService, $cordovaGeolocation) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.current_user = {};
var current_user = AuthService.getUser();
//if user is already logged in
if(current_user) {
//If facebook login
if (current_user && current_user.provider == "facebook") {
$scope.current_user.email = current_user.facebook.displayName;
$scope.current_user.image = current_user.facebook.profileImageURL;
}
//If email login
else {
/*Google Map setting*/
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
}, function(error){
console.log("Could not get location");
});
$scope.current_user.email = current_user.password.email;
$scope.current_user.image = current_user.password.profileImageURL;
}
//No user is currently logged in
} else {
$state.go('app.start');
}
//Logout Function
$scope.logout = function(){
AuthService.doLogout();
$state.go('app.start');
};
})
Services.js (Firebase Authentication Service):
angular.module('socialAuth',[])
.service('AuthService', function($q){
var _firebase = new Firebase("https://logfirebase.firebaseio.com/");
// var _firebase = new Firebase("https://geomuse-169214.firebaseio.com");
// var config = {
// apiKey: "AIzaSyBwdvuilAWOU9DttaGPabpKsHIDHJOuF1Q",
// authDomain: "geomuse-169214.firebaseapp.com",
// databaseURL: "https://geomuse-169214.firebaseio.com",
// projectId: "geomuse-169214",
// storageBucket: "geomuse-169214.appspot.com",
// messagingSenderId: "103764525324"
// };
// firebase.initializeApp(config);
// var rootRef = firebase.database().ref();
this.userIsLoggedIn = function(){
var deferred = $q.defer(),
authService = this,
isLoggedIn = (authService.getUser() !== null);
deferred.resolve(isLoggedIn);
return deferred.promise;
};
this.getUser = function(){
return _firebase.getAuth();
};
this.doLogin = function(user){
var deferred = $q.defer();
_firebase.authWithPassword({
email : user.email,
password : user.password
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doFacebookLogin = function(){
var deferred = $q.defer();
_firebase.authWithOAuthPopup("facebook", function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doSignup = function(user){
var deferred = $q.defer(),
authService = this;
_firebase.createUser({
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
password : user.password,
gender : user.gender
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
// After signup we should automatically login the user
authService.doLogin(user)
.then(function(data){
// success
deferred.resolve(data);
},function(err){
// error
deferred.reject(err);
});
}
});
return deferred.promise;
};
this.doLogout = function(){
_firebase.unauth();
};
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="lib/ion-md-input/css/ion-md-input.min.css" rel="stylesheet">
<link href="lib/ionic-material/dist/ionic.material.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/geomuse.css" rel="stylesheet">
<link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-material/dist/ionic.material.min.js"></script>
<script src="lib/ion-md-input/js/ion-md-input.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!--Googple maps plugin-->
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAq9weEMgdVahLcdbvokguOZDuZ3PVVyig&sensor=true"></script>
<!--Firebase-->
<script src="lib/firebase/firebase.js"></script>
<script src="lib/angularfire/dist/angularfire.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
muser.html (Logged in view):
<ion-view view-title="Login" align-title="left">
<ion-content>
<div id="map"></div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'ionic-material', 'ionMdInput', 'ngCordova', 'firebase', 'socialAuth'])
.run(function($ionicPlatform, $state, AuthService, $rootScope) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
AuthService.userIsLoggedIn().then(function(response)
{
if(response === true)
{
$state.go('app.muser');
}
else
{
$state.go('auth.connect');
}
});
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
// UI Router Authentication Check
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if (toState.data.authenticate)
{
AuthService.userIsLoggedIn().then(function(response)
{
if(response === false)
{
event.preventDefault();
$state.go('auth.connect');
}
});
}
});
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// Turn off caching for demo simplicity's sake
$ionicConfigProvider.views.maxCache(0);
/*
// Turn off back button text
$ionicConfigProvider.backButton.previousTitleText(false);
*/
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.activity', {
url: '/activity',
views: {
'menuContent': {
templateUrl: 'templates/activity.html',
controller: 'ActivityCtrl'
},
'fabContent': {
template: '<button id="fab-activity" class="button button-fab button-fab-top-right expanded button-energized-900 flap"><i class="icon ion-paper-airplane"></i></button>',
controller: function ($timeout) {
$timeout(function () {
document.getElementById('fab-activity').classList.toggle('on');
}, 200);
}
}
}
})
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.register-email', {
url: '/register-email',
views: {
'menuContent': {
templateUrl: 'templates/register-email.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.forget-password', {
url: '/forget-password',
views: {
'menuContent': {
templateUrl: 'templates/forget-password.html',
controller: 'ForgetPasswordCtrl'
},
'fabContent': {
template: ''
}
}
})
.state('app.signup', {
url: '/signup',
views: {
'menuContent': {
templateUrl: 'templates/auth/sign-up.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.connect', {
url: '/connect',
views: {
'menuContent': {
templateUrl: 'templates/auth/connect.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.muser', {
url: '/muser',
views: {
'menuContent': {
templateUrl: 'templates/app/muser.html',
controller: 'MuserCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/start');
});
Help would be greatly appreciated

update index.html in angularjs

Currently our website in angularjs is not updated by latest javascript version without doing hard refresh is browser. In order to update it on real time basis, we have started sending a custom header (APP-VERSION) in our rest API based on which we can reload the page which results in updating the website by latest javascript version.
This version comparision code is written in javascript is the HTTP interceptor which is not updated on client side.
In order to update index.html, we have tried various scenario which are as follows:-
1.We have changed the name of index.html to default.html but still it is not updated on client side.
2.We have changed the path (/test/index.html) of index.html, still its not working.
3.We have used on-page script on every page, we got a warning "Trying to load angularjs twice".
4.We have added the custom header (add_header Cache-Control no-cache;) in the config file on nginx which is also not working/
Please help us how to forcefully update the index.html on client side.
Please find the code index.html, HTTPInterceptor, and route.js
index.html:-
<!DOCTYPE html>
<html>
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/WebRupee/2.0/font.min.css" />
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<!--<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.mobile.all.min.css"/>
-->
<link rel="stylesheet" href="/css/mrConsultant.min.css?ver=##cssVer">
<!-- <link rel="stylesheet" href="css/preLoginPartner.css"> -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/">
<!-- Google Tag Manager -->
<script>
##gtmScript
</script>
<!-- End Google Tag Manager -->
</head>
<body ng-app="myApp" ng-cloak layout="column">
<div flex layout="column">
<div ng-view flex layout="column"></div>
</div>
<!-- Google Tag Manager (noscript) -->
<noscript>
##gtmNoScript
</noscript>
<!-- End Google Tag Manager (noscript) -->
</body>
<script type="text/javascript" src="js/mrConsultant.min.js?ver=##jsVer"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js" ></script>
<script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.timezones.min.js" ></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js" async></script>-->
<script src="http://ngmaterial.assets.s3.amazonaws.com/svg-assets-cache.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.1/angular-sanitize.min.js"></script>
<noscript>test scritp</noscript>
</html>
HTTPInterceptor:-
myApp.factory('HTTPInterceptor', ['$location','$q','API_URL','version','CookieService','$templateCache','$window',function ($location,$q,API_URL,version,CookieService,$templateCache,$window) {
return {
'request': function (config) {
if ((config.url.indexOf('.html') ==-1) && (config.url.indexOf('.svg')==-1)) {
config.url = API_URL + config.url;
if ((config.url.indexOf('/forgot-password-consultant')==-1) && (config.url.indexOf('/reset-password-consultant')==-1)) {
config.headers['Authorization'] = CookieService.getCookie('AUTH_TOKEN');
}
config.headers['Accept'] = "application/vnd.refer.v1+json";
}
return config;
},
'response': function (resp) {
function createCustomAlert() {
d = document;
if(d.getElementById("website-update")) return;
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "website-update";
style = mObj.appendChild(d.createElement("style"));
style.innerHTML = "#import url('https://fonts.googleapis.com/css?family=Roboto')";
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "website-update-card";
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode("UPDATE ALERT"));
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = "A new version of Refer is available now. Update now for better performance.";
msg1 = alertObj.appendChild(d.createElement("p"));
msg1.innerHTML = "If you are on an important task, continue your work and you can update on next page.";
updateBtn = alertObj.appendChild(d.createElement("button"))
updateBtn.id = "website-update-btn";
updateBtn.innerHTML = "Update Now";
updateBtn.onclick = function() { clearTemplateCache();return true; }
notUpdateBtn = alertObj.appendChild(d.createElement("button"))
notUpdateBtn.id = "website-update-notnow";
notUpdateBtn.innerHTML = "Not now";
notUpdateBtn.onclick = function() { removeCustomAlert();return false; }
}
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
}
function clearTemplateCache() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
$templateCache.removeAll();
$window.location.reload();
}
if (resp.status === 401) {
$templateCache.removeAll();
$window.location.reload();
$location.path('/logout');
}/*else if(resp.status === 200 && resp.headers('app-version') != null && resp.headers('app1-version') != version){
createCustomAlert();
}*/
return resp;
},
'responseError': function (rejection) {
if(rejection.status === 401) {
$templateCache.removeAll();
$location.path('/logout');
}
return $q.reject(rejection);
}
};
}]);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('HTTPInterceptor');
}]);
route.js:-
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: true,
rewriteLinks: true
});
}
$routeProvider.when('/unicorn-:startups-:consultant-:register', {
templateUrl: 'views/registerCampaign.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/register', {
templateUrl: 'views/register.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/login', {
templateUrl: 'views/login3.html',
controller: 'LoginController',
controllerAs: 'loginCtrl',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/forgot-password', {
templateUrl: 'views/forgotPassword.html',
controller: '' +
'forgotPasswordController'
}).when('/reset-password/:token/:sm', {
templateUrl: 'views/resetPassword.html',
controller: 'resetPasswordController'
}).when('/logout', {
resolve: {
auth: ['$location', 'UserService', function ($location, UserService) {
UserService.logout();
$location.path('/login');
$location.replace();
}]
}
}).when('/', {
templateUrl: 'views/dashboard.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/dashboard', {
templateUrl: 'views/dashboard1.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/jobs/:jobType', {
templateUrl: 'views/jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/jobs.html'
} else {
$location.path('/login');
}
}]
}
}).when('/job-detail/:jobId', {
templateUrl: 'views/job-detail.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/job-detail.html'
} else {
$location.path('/login');
}
}]
}
}).when('/direct-apply/:jobId', {
templateUrl: 'views/apply-new.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-new.html'
} else {
$location.path('/login');
}
}]
}
}).when('/performance', {
templateUrl: 'views/performance.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/performance')
} else {
$location.path('/login');
}
}]
}
}).when('/calendar', {
templateUrl: 'views/calender.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/calendar')
} else {
$location.path('/login');
}
}]
}
}).when('/tracker', {
templateUrl: 'views/tracker.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/tracker')
} else {
$location.path('/login');
}
}]
}
}).when('/internal-jobs', {
templateUrl: 'views/internal-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/internal-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/assigned-jobs', {
templateUrl: 'views/assigned-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/assigned-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-candidates/:jobId', {
templateUrl: 'views/suggested-candidates.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/suggested-candidates.html'
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-apply/:jobId', {
templateUrl: 'views/apply-suggested.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-suggested.html'
} else {
$location.path('/login');
}
}]
}
}).when('/edit-candidate/:jobId', {
templateUrl: 'views/edit-candidate.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/edit-candidate.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database', {
templateUrl: 'views/database.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search', {
templateUrl: 'views/database-search.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search-result', {
templateUrl: 'views/database-search-result.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search-result.html'
} else {
$location.path('/login');
}
}]
}
}).when('/review-compare', {
templateUrl: 'views/review-compare.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/review-compare.html'
} else {
$location.path('/login');
}
}]
}
}).when('/add-new', {
templateUrl: 'views/add-contact.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/add-contact.html'
} else {
$location.path('/login');
}
}]
}
})
.otherwise({
redirectTo: '/'
});
}]);
myApp.run(['$rootScope', '$templateCache', function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
}]);
nginx settings:-
location / {
add_header Cache-Control no-cache;
root D:\refer-workspace\consultant_web;
try_files $uri $uri/ /index.html/ =404;
expires -1;
}
Thanks in advance.

Modify method to show success/failed Message. AngularJS

I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.
you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate

AngularJS Routing not updating the menu items but loading the url and views correctly

I am doing token based authentication using MEAN stack. My application has to show Home, Signin and Signup when there is no token present i.e when a user is not logged in and Home, Me and Logout when there is a token i.e user is logged in. All my server side functionality is working fine with Signin,Signup,Logout. URL redirection in the address bar and rendering of the view is happening correctly , but the Menu items are not updating accordingly.Its getting updated only when i hit a manual refresh. Please help !
Index.html (Omitted includes):
<body ng-app="app">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" data-ng-controller="authCtrl">
<!-- data-ng-controller="authCtrl" -->
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#/">Angular Restful Auth</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a ng-href="#/">Home</a></li>
<li data-ng-show="token"><a ng-href="#/me">Me</a></li>
<li data-ng-hide="token"><a ng-href="#/login">Signin</a></li>
<li data-ng-hide="token"><a ng-href="#/register">Signup</a></li>
<li data-ng-show="token"><a ng-click="logout()">Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" ng-view="">
</div> <!-- /container -->
</body>
app.js:
'use strict';
var app = angular.module('app', ['ngRoute', 'authControllers', 'authServices']);
var authControllers = angular.module('authControllers', []);
var authServices = angular.module('authServices', []);
var options = {};
options.api = {};
//dev URL
options.api.base_url = "http://localhost:3000";
app.config(['$locationProvider', '$routeProvider',
function($location, $routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'authCtrl'
}).
when('/login', {
templateUrl: 'partials/signin.html',
controller: 'authCtrl'
}).
when('/register', {
templateUrl: 'partials/signup.html',
controller: 'authCtrl'
}).
when('/me', {
templateUrl: 'partials/me.html',
controller: 'authCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
}]);
app.run(function($rootScope, $location, $window, AuthenticationService) {
$rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
//redirect only if both isAuthenticated is false and no token is set
if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication
&& !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {
$location.path("/login");
}
});
});
authControllers.js:
authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
//Admin User Controller (login, logout)
$scope.logIn = function logIn(username, password) {
if (username !== undefined && password !== undefined) {
UserService.logIn(username, password).success(function(data) {
AuthenticationService.isLogged = true;
$window.sessionStorage.token = data.token;
$location.path("/me");
}).error(function(status, data) {
console.log(status);
console.log(data);
});
}
}
$scope.token = $window.sessionStorage.token;
$scope.me = function() {
UserService.me(function(res) {
$scope.myDetails = res;
}, function() {
console.log('Failed to fetch details');
$rootScope.error = 'Failed to fetch details';
})
};
$scope.logout = function logout() {
if (AuthenticationService.isAuthenticated) {
UserService.logOut().success(function(data) {
AuthenticationService.isAuthenticated = false;
delete $window.sessionStorage.token;
$location.path("/");
}).error(function(status, data) {
console.log(status);
console.log(data);
});
}
else {
$location.path("/login");
}
}
$scope.register = function register(username, password, passwordConfirm) {
if (AuthenticationService.isAuthenticated) {
$location.path("/me");
}
else {
UserService.register(username, password, passwordConfirm).success(function(data) {
$location.path("/login");
}).error(function(status, data) {
console.log(status);
console.log(data);
});
}
}
}]);
$scope.token = $window.sessionStorage.token;
This string doesn't bind token to storage property. You should each time update you scope variable and if you are not in digest loop then call apply explicitly.
Actually i tried a different approach that's even better to do it globally once. Injected $rootScope in my controller and assigned the SessionStorage token value.Now it works like a charm with simple change without updating $scope variable in multiple places.
authControllers.controller('authCtrl', ['$rootScope','$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($rootScope,$scope, $location, $window, UserService, AuthenticationService) {
$rootScope.token = $window.sessionStorage.token;
}]);

Categories

Resources