I am uplifting a chat application from AngularJS to VueJS and I don't have much clue about how the AngularJS. There isn't really a great resources available on AngularJS right now to gain some insight.
If someone could help me in this I'd really appreciate it.
I wish to convert this below AngularJS code to VueJS completely.
var app = angular.module('IBMfinder', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider, settings) {
$routeProvider
.when('/main', {
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
.when('/find', {
templateUrl: 'find.html',
controller: 'findCtrl',
})
.when('/chat', {
templateUrl: 'chat.html',
controller: 'chatCtrl',
})
.otherwise({
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
}])
app.controller('userCount', ['$scope', 'socket', function($scope,
socket){
socket.on('userCount', function(amount){
$scope.online = amount;
})
}]);
app.controller('welcomeCtrl', ['$scope', '$location', 'settings',
'socket', function($scope, $location, settings, socket){
$scope.users = 13;
if(settings.getUsername()!==""){
socket.emit('delete');
settings.reset();
}
$scope.enter = function(){
settings.setUsername($scope.name);
$location.path('/find');
}
}]);
app.controller('findCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', function($scope, $location, settings,
socket, $rootScope){
$scope.username = settings.getUsername();
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
if(settings.exists){
socket.emit('delete');
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('match', function (data) {
settings.setPartner(data['username'], data['id']);
$location.path('/chat');
});
}]);
app.controller('chatCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', '$timeout', '$window', '$interval',
function($scope, $location, settings, socket, $rootScope, $timeout,
$window, $interval){
var typing = false;
var focus = true;
var titleTimer;
var onFocus = function(){
focus = true;
$interval.cancel(titleTimer);
document.title = 'Chat-Box';
}
var onBlur = function(){
focus = false;
}
$window.onfocus = onFocus;
$window.onblur = onBlur;
$scope.username = settings.getUsername();
$scope.partnerTyping = false;
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('incoming message', function(data){
if($scope.chatlog[$scope.chatlog.length-1]){
if($scope.chatlog[$scope.chatlog.length-1].sentby == data.userID){
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: '',
chatmessage: data.message
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
if(!focus){
document.title = 'New Message!';
$interval.cancel(titleTimer);
titleTimer = $interval(function(){
if(document.title == 'New Message!'){
document.title = 'Chat-Box';
}else{
document.title = 'New Message!';
}
}, 1000)
}
});
socket.on('aborted', function(data){
alert('Your partner left, sorry!');
socket.emit('delete');
settings.reset();
location.href = "index.html";
})
$scope.typing = function(){
if(!typing){
socket.emit('typing', settings.getID());
typing = true;
var stop = $timeout(function() {
typing = false;
socket.emit('stop typing', settings.getID());
}, 2000);
}
}
socket.on('typing', function(data){
$scope.partnerTyping = true;
$('#chatbox').scrollTop(10000);
})
socket.on('stop typing', function(data){
$scope.partnerTyping = false;
$('#chatbox').scrollTop(10000);
})
$scope.sendMessage = function(){
if($scope.message==""){
}else{
socket.emit( 'new message', {
message:$scope.message,
partner:$scope.partner,
partnerID: settings.getID()
});
}
$scope.message = "";
}
$scope.partner = settings.getPartner();
}]);
app.service('settings', function() {
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
this.setExists = function(bool){
this.exists = bool;
}
this.setUsername = function(uname){
this.username = uname;
}
this.getUsername = function(){
return(this.username);
}
this.setUserID = function(id){
this.userdata.id = id;
}
this.getuserdata = function(){
return(this.userdata);
}
this.setPartner = function(uname, id){
this.partner = uname;
this.partnerID = id;
}
this.getPartner = function(){
return(this.partner);
}
this.getID = function(){
return(this.partnerID);
}
this.reset = function(){
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
}
});
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
disconnect: function(id){
socket.disconnect(id);
}
};
});
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
app.directive('schrollBottom', function () {
return {
scope: {
schrollBottom: "="
},
link: function (scope, element) {
scope.$watchCollection('schrollBottom', function (newValue) {
if (newValue)
{
$(element).scrollTop(100000);
}
});
}
}
})
It'd be great if someone could point me to any great resources. I've not had any luck since past week regarding this.
Video Tutorials
https://www.youtube.com/watch?v=i9MHigUZKEM
https://egghead.io/courses/angularjs-fundamentals
Text Tutorials
https://docs.angularjs.org/tutorial
Try to search on google first.
If you can't understand something ask a concrete question with an example (it doesn't have to be the full code) so we can help you better.
I don't know if you have experience with Vue.js, I can tell you worse what those tutorials will explain way better. AngularJS uses a different approach than Vue, Angular 2+ or React.
Those frameworks use a component approach so you divide the app into multiple components that have properties.
Angular use an MVC-ish approach, you define modules with angular. module those modules can have external or core dependencies defined in the array.
A module can have a router, a router will define the views and the controller of each view. The views have angular directives and HTML, and the controllers have the logic.
Use one of those tutorials to learn more.
i maked one website with routes by $routeProvider, i made controller for every page and it looks like:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/category/Web development', {
templateUrl: 'pages/web-dev.html',
controller: 'catCtrl'
})
.when('/category/Game Programming', {
templateUrl: 'pages/game-programming.html',
controller: 'catCtrl2'
})
myApp.controller('catCtrl', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/web-dev")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category" )
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
myApp.controller('catCtrl2', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/game-programming")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category")
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
as you can see, both controllers have same content, but i would like to make only one controller for different pages, any advice how i could make it? i tryed to set same controller in $routeProvider but its not working :(
I think your best approach would be something like this:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/category/:category', {
templateUrl: function (urlattr) {
return '/category/' + urlattr.category + '.html';
},
controller: 'CategoryController',
controllerAs: 'categoryCtrl'
}).otherwise({
redirectTo: '/category/web_development'
});
}]);
myApp.controller('CategoryController', ['$routeParams', '$http', function ($routeParams, $http) {
var categoryCtrl = this;
// Use $http based on $routeParams.category
}]);
I'm having trouble passing through a uid into the $state.go function.
Here is my controller:
.controller('chatCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory,$stateParams) {
$scope.data = {};
$scope.session_id= sessionStorage.getItem('session_id');
var sid = $scope.session_id;
if($scope.session_id == null){
$state.go('login');
}
else {
var cload = 'https://m.socialnetwk.com/home/app/chat_load.php';
$http.post(cload, {id : $scope.session_id}).then(function (res){
$scope.chat = res.data;
});
$scope.chat = {};
$scope.openModal = function(id) {
$scope.selectedId = id;
$state.go('chat2',{uid: $scope.selectedId});
}
}
})
.controller('chat2Ctrl', function($scope,$http,$ionicPopup,$state,$ionicHistory,$stateParams) {
$scope.data = {};
$scope.id = {};
$scope.session_id= sessionStorage.getItem('session_id');
var sid = $scope.session_id;
if($scope.session_id == null){
$state.go('login');
}
else {
var pmloaddd = 'https://m.socialnetwk.com/home/app/upml.php';
$http.post(pmloaddd, {id : $state.params.uid}).then(function (res){
$scope.pmload = res.data;
});
}
})
Here is my app.js:
$stateProvider
.state('chat2', {
url: '/page9',
params: {
uid: null
},
templateUrl: 'templates/chat2.html',
controller: 'chat2Ctrl'
})
There are two mistakes
Did not add the parameter to the URL property of your state configuration
And $state.params.uid is invalid.
Use the below solution.
Your app.js
$stateProvider
.state('chat2', {
url: '/page9/:uid', //added the parameter here
params: {
uid: null
},
templateUrl: 'templates/chat2.html',
controller: 'chat2Ctrl'
})
Your else part of the Chat2 controller should be as below
if($scope.session_id == null){
$state.go('login');
}
else {
var pmloaddd = 'https://m.socialnetwk.com/home/app/upml.php';
// modified the below line
$http.post(pmloaddd, {id : $stateParams.uid}).then(function (res){
$scope.pmload = res.data;
});
LIVE DEMO
First you need to pass it with url and then you can access it like--
$stateParams.
$stateProvider
.state('chat2', {
url: '/page9/:uid',
controller:'name of yout controller',
controller: function($stateParams){
$stateParams.uid //*** Exists! ***//
}
});
then you can access like this:-
$stateparams.uid at controller.
You can also refer this link--Url routing--stateParams Service
I dont understand why but when i console.log() both box and box.color its telling me its undefined...I tried many different methods to solve this problem but it all failed.
Cloud9
Plunker
And here is script.js:
var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies"])
app.provider("box", function ()
{
var hex = "SomeColor";
var UID = 3;
return {
setColor: function (value)
{
UID = value
},
$get: function ()
{
return {
color: hex
}
}
}
})
app.config(function ($routeProvider, $cookiesProvider) {
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/Test' , {
template: '<h3>This is just a testing phase</h3>',
controller: 'Testing'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('Testing', ["$scope","roomService", "roomProvider", function($scope, roomService, roomProvider){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log("This is from the Controller Provider: " + roomProvider.$get)
}
])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://chattappp.firebaseio.com/");
return $firebaseAuth(ref);
}
]);
app.factory("Ref", function(){
var ref = new Firebase("https://chattappp.firebaseio.com/")
return ref;
})
app.factory("UniPosts" , function(){
var ref = new Firebase("https://postss.firebaseio.com/")
return ref;
});
app.service('getCookieService', ["$cookieStore", "$scope",
function($cookieStore, $scope){
this.getCookie = function(name){
$cookieStore.get(name)
}
}
])
roomController.js:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http",
function($scope, Auth, Ref, AuthService, roomService, $http,box) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID)
console.log(box) //Undefined...
console.log("From Provider : " + box.color)//box.color is undefined..
});
}
])
//window.location.hash = "/Test"
EDIT 2: Ok Now it works but im confused on how to use it on app.config.. i My provider is Hash:
app.provider("Hash", function ()
{
var UID = 0;
return {
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: function()
{
return UID;
}
}
}
}
})
And when it goes to the controller i set the hash and get the has ... roomControler.js:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash",
function($scope, Auth, Ref, AuthService, roomService, $http,Hash) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID);
Hash.setHash(redirectPage);
console.log("From Provider : " + Hash.getHash())
window.location.hash = "/Test"
});
}
])
Now what i want to do is in my app.config() i want to say when it is in Hash.getHash() Go to template: , and controller:
So something like this....
app.config(function ($routeProvider, $cookiesProvider, Hash) {
$routeProvider.
when('/' + Hash.getHash(), {
template: '<h4> Your in Room',
controller: 'Test
})
});
app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log(Hash.getHash())//This Logs right. :D
}
])
EDIT 3
What i was trying to say earlier was that i want to somehow configure the randomly generated Hash in my app.config() when statements. so in my app.config. WHEN the USER is in /RANDOMLYGENERATEDHASH have a template: '<h1>Test</h1>' . This is what i tried but dosent workk...
It is the fourth one on the .when() Statements..
app.config(function ($routeProvider, $cookiesProvider, HashProvider){
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/' + HashProvider , {
templete: '<h1>Test</h1>'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
And here is the provider now..
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
EDIT 4
Ok This is my roomcontroller.js Now..:
(Important detail at bottom of controller)
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash","$routeParams",
function($scope, Auth, Ref, AuthService, roomService, $http,Hash, $routeParams) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID);
Hash.setHash(redirectPage);
console.log("From Provider : " + Hash.getHash())
$routeParams.hash = Hash.getHash()
});
}
])
and script.js(Note this is not the only ones i have. You can see all other on above link on Cloud9(Plunk not updated)):
var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies", 'ngMessages'])
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
app.config(function ($routeProvider, $cookiesProvider, HashProvider){
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/:Hash', {
template: '<h1>TEST TEST</h1>',
controller: 'any controller'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log(Hash.getHash())
}
])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://chattappp.firebaseio.com/");
return $firebaseAuth(ref);
}
]);
app.factory("Ref", function(){
var ref = new Firebase("https://chattappp.firebaseio.com/")
return ref;
})
app.factory("UniPosts" , function(){
var ref = new Firebase("https://postss.firebaseio.com/")
return ref;
});
app.service('getCookieService', ["$cookieStore", "$scope",
function($cookieStore, $scope){
this.getCookie = function(name){
$cookieStore.get(name)
}
}
])
[1]: https://ide.c9.io/amanuel2/chattapp
[2]: https://plnkr.co/edit/ToWpQCw6GaKYkUegFjMi?p=preview
There are two problems in your code:
Definition of "roomController"
app.controller('roomController', ["$scope", "Auth", "Ref",
"AuthService", "roomService","$http",
function($scope, Auth, Ref, AuthService, roomService,
$http,box) {})
Just match the parameters and their declarations and you will see that you missed a declaration for the "box" parameter. The correct "roomController" definition should be like this:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
function($scope, Auth, Ref, AuthService, roomService, $http,box)
"box" provider. You defined "setColor" method as the configuration method of provider, but you are trying to use it as a provider result method. The corrected version should be like this:
app.provider("box", function ()
{
var hex = "SomeColor";
var UID = 3;
return {
$get: function ()
{
return {
color: hex,
setColor: function (value)
{
UID = value
}
}
}
}
})
Angular Providers
Answer to EDIT2:
You defined HashProvider. To configure it in app.config you should pass argument as HashProvider (not just Hash, BUT when you will try to use it anywhere except app.config you should inject it as Hash). So your app.config declaration should be like this:
app.config(function ($routeProvider, $cookiesProvider, HashProvider)
...and to let you access the getHash method it's necessary to move it to the provider configuration, for example like this:
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
Answer to EDIT3:
Now I got what you are trying to do. And the thing is that you are trying to do it wrong :). The right way is more simple. You have to configure route with param, for example like this:
.when('/:hash', {
template: '<h1>TEST TEST</h1>',
controller: 'any controller'
})
And place it just after your last route. After that, in controller you may access hash by using $routeParams object. For example like this:
$routeParams.hash
And after that in controller you may analyze if it's right hash and do necessary stuff, or redirect user somewhere if hash is invalid.
I am trying to get a header to update after login. I have used both $on and $watch in this effort to no avail. When I refresh it works correctly. Code is as follows below.
header.html (missing excess nav bar code for simplicity)
<li><a ng-href="#/login" ng-hide="showMenu">Login</a></li>
<li><a ng-href="#/signup" ng-hide="showMenu">Signup</a></li>
<li>Logout</li>
app.js
$stateProvider
.state('app', {
url: '',
views: {
'header': {
templateUrl: 'views/partials/_header.html',
controller: 'HeaderCtrl'
}
}
})
header.js (The broadcast fires correctly as demonstrated by the console.logs)
angular.module('urbinsight')
.controller('HeaderCtrl', function ($scope, $rootScope, $state, $location, UserAuthFactory, AuthFactory) {
$scope.logout = function () {
UserAuthFactory.logout();
$rootScope.$broadcast('loginStateChange');
$location.path('/');
};
$scope.showMenu = AuthFactory.loggedStatus();
$rootScope.$on('loginStateChange', function(){
console.log($scope.showMenu)
$scope.showMenu = AuthFactory.loggedStatus();
console.log($scope.showMenu)
})
})
authService
angular.module('urbinsight.services')
.factory('AuthFactory', function ($window) {
var isLogged = false;
return {
check: function() {
if ($window.sessionStorage.token && $window.sessionStorage.user) {
isLogged = true;
} else {
isLogged = false;
delete this.user;
}
},
loggedStatus: function() {
return isLogged;
},
changeLoggedStatus: function() {
isLogged = !(isLogged);
}
};
})
login function + broadcast
login.submit = function () {
var username = user.username,
password = user.password;
if (username !== undefined && password !== undefined) {
UserAuthFactory.login(username, password).success(function(data) {
$rootScope.showMenu = true
// AuthFactory.isLogged = true;
AuthFactory.changeLoggedStatus();
AuthFactory.user = data.user.username;
AuthFactory.userRole = data.user.role;
$rootScope.$broadcast('loginStateChange');
$window.sessionStorage.token = data.token;
$window.sessionStorage.user = data.user.username;
$window.sessionStorage.userRole = data.user.role;
$location.path('/');
}).error(function(status) {
$window.alert('Oops something went wrong!');
});
} else {
$window.alert('Invalid credentials');
}
};
Please tell me what I am doing wrong.
You have set the "$rootScope.showMenu = true" in your login controller. But in your header controller you also have "$scope.showMenu = AuthFactory.loggedStatus();"
So i would remove this line from your header controller
$scope.showMenu = AuthFactory.loggedStatus();
Since you want your header html to react to $rootscope showMenu variable directly