console.log('js');
var myApp = angular.module('myApp', ["ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrlnp: 'views/partials/logIn.html',
controller: 'LoginController as lc'
}).when('/register', {
templateUrl: 'views/partials/register.html',
controller: 'RegisterController as rc'
}).when('/login', {
templateUrl: 'views/partials/logIn.html',
controller: 'LoginController as lc'
}).when('/userProfile', {
templateUrl: 'views/partials/userProfile.html',
controller: 'UserProfileController as uc'
});
}); //end config
//global variables
myApp.controller('DefaultController', DefaultController);
myApp.controller('RegisterController', RegisterController);
myApp.controller('LoginController', LoginController);
myApp.controller('UserProfileController', UserProfileController);
function DefaultController(navBarService) {
var vm = this;
console.log('inside of DefaultController');
navBarService.toggleHeader(vm.toggleHeader);
vm.toggleHeader = true;
} //end DefaultController
function RegisterController(credentialsService) {
var vm = this;
console.log('RegisterController');
vm.register = function() {
if (vm.firstNameRegister === undefined || vm.lastNameRegister === undefined || vm.emailRegister === undefined || vm.passwordRegister === undefined || vm.zipcode === undefined) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else if (vm.firstNameRegister === '' || vm.lastNameRegister === '' || vm.emailRegister === '' || vm.passwordRegister === '' || vm.zipcode === null) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else {
var userCredentials = {
firstName: vm.firstNameRegister.toLowerCase(),
lastName: vm.lastNameRegister.toLowerCase(),
email: vm.emailRegister,
password: vm.passwordRegister,
zipcode: vm.zipcode
}; //end userCredentials
credentialsService.sendRegister(userCredentials);
} //end of conditional statement
}; //end register function
} //end register controller
function LoginController(credentialsService) {
var vm = this;
console.log('LoginController');
vm.login = function() {
if (vm.emailLogin === undefined || vm.passwordLogin === undefined) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else {
var userCredentials = {
email: vm.emailLogin,
password: vm.passwordLogin
}; //end userCredentials
console.log(userCredentials);
credentialsService.sendLogin(userCredentials).then(function() {
console.log('back from the service with', credentialsService.response);
if (credentialsService.response === 'Match!!!') {
var id = userCredentials.email;
credentialsService.getUsers(id);
window.location.replace("http://localhost:7138/#!/userProfile");
} else {
sweetAlert({
title: "Error!",
text: "No user found",
type: "error"
}); //end of sweetAlert
} //end of else
}); //end of then
} //end of else conditional statement
}; //end log in function
} //end register controller
function UserProfileController() {
console.log('inside of UserProfileController');
var vm = this;
vm.getUserInfo = function() {
console.log('inside of getUserInfo');
}; //end of getUserInfo
} //end of userProfile
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rental app</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="vendors/angular.min.js" charset="utf-8"></script>
<script src="vendors/angular-route.min.js" charset="utf-8"></script>
<script src="scripts/client.js" charset="utf-8"></script>
<script src="scripts/services/credentialsService.js" charset="utf-8"></script>
<script src="scripts/services/navBarService.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<link rel="stylesheet" href="styles/register.css">
</head>
<body ng-app='myApp'>
<div class="container" ng-controller='DefaultController as dc'>
<div class="Navigation" ng-if='dc.toggleHeader'>
<h1>Navigation</h1>
</div>
<ng-view></ng-view>
</div>
</body>
</html>
When someone hits the login or registration partial page, I want the Navigation text to not appear. The problem is that I cant talk to different controllers. In my index.html page i have the navigation div "ng-if='dc.toggleHeader'" set to true in my default controller: "vm.toggleHeader = true;". When the user navigates to the login or register controller, how do i set vm.toggleHeader = false so the nav div will hide. Would broadcasting help me here?
When the user navigates to the login or register controller, how do i set vm.toggleHeader = false so the nav div will hide.
The DefaultController can use the $route service to the determine current templateUrl in use:
function DefaultController(navBarService, $route) {
var vm = this;
console.log('inside of DefaultController');
navBarService.toggleHeader(vm.toggleHeader);
vm.toggleHeader = true;
vm.$doCheck = function() {
vm.toggleHeader = true;
if ($route.current.templateUrl == 'views/partials/logIn.html') {
vm.toggleHeader = false;
};
if ($route.current.templateUrl == 'views/partials/register.html') {
vm.toggleHeader = false;
};
};
}
On each digest cycle, the $doCheck function will check the current route and set toggleHeader to the appropriate value.
For more information, see
AngularJS $route Service API Reference
AngularJS $compile Service API Reference - Life Cycle Hooks
Related
hey i'm doing a login in ionic 1... i couldn't save my auth on local storage, before i do this local storage, i used session storage but everytime people want to open my apps again, it should logged in again..
this is my controllers.
.controller('login', function($scope, $http, $ionicPopup, $state, $ionicHistory, $localStorage, $window) {
// localhost
var baseUrl = 'http://developing/alhikmah_api/v1/mobile/auth/login';
$scope.showAlert = function(msg) {
$ionicPopup.alert({
title: msg.title,
template: msg.message,
okText: 'Baik',
okType: 'button-positive'
})
}
if ($localStorage.getItem('nis') !== null && $localStorage.getItem('token') !== null) {
$scope.showAlert({
title: "Pesan",
message: "Selamat Datang Kembali :)"
});
$state.go('tab.home');
}
$scope.login = function() {
if (!$scope.login.nis) {
$scope.showAlert({
title: "Informasi",
message: "Nomor Induk Santri Harap di Isi !"
})
} else if (!$scope.login.pass) {
$scope.showAlert({
title: "Informasi",
message: "password mohon diisi"
})
} else {
$http.post(baseUrl, {
username: $scope.login.nis,
password: $scope.login.pass,
role: "santri"
}).success(function(data) {
console.log(data);
if (data.success == false) {
$scope.showAlert({
title: "Information",
message: data.message
})
$scope.login.nis = '';
$scope.login.pass = '';
} else {
$localStorage.setItem('id', data.data[0].id);
$localStorage.setItem('nis', data.data[0].username);
$localStorage.setItem('token', data.token);
$scope.showAlert({
title: "Information",
message: data.message
})
$state.go('tab.home');
}
});
}
}
})
everything works fine if i use sessionstorage instead of localstorage. But all i want is to make people not log in anymore in my apps.
thanks
I am assuming you are referring to ngStorage module
use ngStorage js file like this (make sure you load it after angularjs is loaded, notice the order of script tags) :
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js>
then you can use $localStorage in your controller, if not use $window.localStorage
I have simple angular app with a Main Controller and a child controller. Maincontroller loads the login page and on successfull login, a welcome page is loaded in using the child controller. The app is simple one and is working. My issue is to set the logged in user name after successfull login.
.controller('mainController', function($rootScope, $location, Auth) {
var vm = this;
vm.loggedinUser = Auth.getActiveUser();
console.log(">>>>>> ", vm.loggedinUser);
//check to see user is logged in for every request made
$rootScope.$on('$routeChangeStart', function() {
vm.loggedIn = Auth.isLoggedIn();
});
My html page is simple:
<body ng-app="bookapp" ng-controller="mainController as main">
..
<li class="navbar-text">Hello {{ main.loggedinUser }}! >
Issue is that loggedinUser value is not displayed.
1) For it to work i have to initialize the loggedinUser value within the routechange listener.(moving the line to within listener works). Why is it so?
2) Also note that the console.log statement prints the real value after log in and when the welcome page is displayed. But variable value is set in main Controller during the application load itself(login page) and can only be changed through route change listener. It is not re-initialized during welcome page load.
You can either pass an object reference to the controller or use the $watch service to evaluate the the getActiveUser function every digest and update the controller scope.
angular.module("bookapp", []);
angular.module("bookapp").controller("mainCtrl", function(Auth) {
var vm = this;
vm.userData = Auth.data;
vm.login = function() {
Auth.data.loginTimeStamp = new Date();
Auth.data.user = "TestUser";
};
});
angular.module("bookapp").factory("Auth", function() {
var data = {
loginTimeStamp: null,
user: null,
};
return {
data: data
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="bookapp">
<div ng-controller="mainCtrl as main">
<p>Hello {{ main.userData.user }}!</p>
<button ng-click="main.login()">Log In</button>
</div>
</body>
angular.module("bookapp", []);
angular.module("bookapp").controller("mainCtrl", function($scope, Auth) {
var vm = this;
$scope.getUser = Auth.getActiveUser;
vm.login = function() {
Auth.setActiveUser("TestUser");
debugger;
};
$scope.$watch(function(scope) {
return scope.getUser();
}, function(newValue) {
vm.loggedinUser = newValue;
debugger;
});
});
angular.module("bookapp").factory("Auth", function() {
var data = {
loginTimeStamp: null,
user: null,
};
return {
getActiveUser: function() {
return data.user;
},
setActiveUser: function(userName) {
data.user = userName;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="bookapp">
<div ng-controller="mainCtrl as main">
<p>Hello {{ main.loggedinUser }}!</p>
<button ng-click="main.login()">Log In</button>
</div>
</body>
Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
<div ng-controller="gridController">
<!-- Initialise the grid with ng-init call -->
<div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
</div>
</div>
<script src="Scripts/ng/angular.min.js"></script>
<script src="Scripts/ng-grid/ui-grid.min.js"></script>
<link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />
<script type="text/javascript">
var app = angular.module('app', ['ui.grid']);
app.controller("gridController",
["$scope", "$attrs", "$element", "$compile", "$http", "$q",
function ($scope, $attrs, $element, $compile, $http, $q)
{
$scope.urlList = "YourSourceUrl";
function fnGetList(url)
{
var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
deferred.resolve(data);
})
.error(function (errorMessage)
{
alert(errorMessage);
deferred.reject;
});
return deferred.promise;
};
$scope.GetGridData = function (url)
{
console.log("In GetGridData: " + "Getting the data");
// Test Only - un-comment if you need to test the grid statically.
//$scope.loadData = ([
// {
// "UserName": "Joe.Doe",
// "Email": "Joe.Doe#myWeb.com"
// },
// {
// "UserName": "Jane.Doe",
// "Email": "Jane.Doe#myWeb.com"
// },
//]);
//return;
fnGetList(url).then(function (content)
{
// Assuming your content.data contains a well-formed JSON
if (content.data !== undefined)
{
$scope.loadData = JSON.parse(content.data);
}
});
};
$scope.gridOptions =
{
data: 'loadData',
columnDef:
[
{ field: 'UserName', name: 'User' },
{ field: 'Email', name: 'e-mail' }
]
};
}
]);
</script>
</body>
Provided from: How do I get data to show up in angular ui.grid from an $http request
The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
type: "POST",
url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
dataType: 'json',
success: function(data){
configData = data;
}
});}
The timer function that is part of the javascirpt is also given below.
var timer = setInterval(function() {
$scope.$apply(updatePage);
}, 500);
var updatePage = function() {
if (typeof configData !== 'undefined')
{
clearInterval(timer);
$scope.loadData = configData;
}
};
I'm coding a web app in html, AngularJS and REST (rest modified for my teachers).
My program should load participants in a select in the openning. But show i.e {{participants.name}} and not {{Jhon}}
The problem is at the moment that would load method "search".
Error:
"Error: Birthday.search is not a function
$scope.updateList#localhost:9000/birthday.js:26:1
#localhost:9000/birthday.js:31:5
e#localhost:9000/node_modules/angular/angular.min.js:36:313
Fe/this.$get
HTML:
<!DOCTYPE html>
<html lang="es" data-ng-app="birthdayApp">
<html>
<head>
<meta charset="utf-8">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="node_modules/angular/angular.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css">
<script src="birthday.js"></script>
</head>
[...]
<body>
<div class="container-fluid" data-ng-controller="BirthdayControllers as birthday">
[...]
<select size="2" class="col-lg-12 col-md-12 col-xs-12">
<option data-ng-repeat="participant in participants | filter:filter"> {{participant.name}} </option>
</select>
[...]
The head its ok?
AngularJS
'use strict';
var app = angular.module("birthdayApp", [])
app.factory('Birthday', function($http) {
return function(errorHandler) {
this.search = function(callback, errorHandler) {
$http.get('/participants').success(callback).catch(errorHandler);
}
}
});
/* Controllers */
app.controller("BirthdayControllers", function($scope, Birthday) {
$scope.participants = null;
var errorHandler = function(error) {
$scope.notificarError(error.data);
};
$scope.updateList = function() {
Birthday.search(function(data) { //here stop, here the problem!
$scope.participants = data;
}, errorHandler);
}
$scope.updateList();
[...]
});
My factories look different. Here's how I do mine:
app.factory('Birthday', function ($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
Controller would look like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).error(function(data, status, headers, config) {
//handle the error
});
You need to return a factory object from the function not another function.
So modify your code like this:
app.factory('Birthday', function($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
It's better to handle the callbacks in the controller, so call the factory method like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).catch(function(error) {
$scope.notificarError(error.data);
});
I am trying to get events from my calendar by using the Google API:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="googleCalendar.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<div id="calendarContainer">
<div>
<button type="button" id="authorize-button"><?= _("Google Calendar Events"); ?></button>
</div>
<div id="content">
<h2><?= _("Events"); ?></h2><br>
<ul id="events"></ul>
</div>
</div>
</body>
</html>
googleCalendar.js:
$(document).ready(function() {
var clientId = '{my_client_id}';
var apiKey = '{my_api_key}';
var scopes = 'https://www.googleapis.com/auth/calendar';
$("#authorize-button").click(function(){
handleClientLoad();
});
function handleClientLoad()
{
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth()
{
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
handleAuthResult);
}
function handleAuthResult(authResult)
{
var authorizeButton = document.getElementById('authorize-button');
if (authResult) {
//authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event)
{
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: false},
handleAuthResult
);
return false;
}
function makeApiCall()
{
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
console.log(resp);
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
});
When I click the button in order to get my events I get nothing. Then I inspect my page and I get this:
Request URL:
https://content.googleapis.com/calendar/v3/calendars/primary/events?key={my_api_key}
Status Code: 404 Not found
Pasting that URL in my browser I get this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
Why do I get a 404 not found and I don't get the list of events from my calendar?