I am trying to do remember me functionality using angularjs,but my email id is
storing in cookies when i click remember me and after logout when i try to
relogin,my mail id should store in username field but it was not showing
what may be the problem below is my code
HTML:
<div class="checkbox" style="margin-bottom: 0px;">
<label>
<input ng-checked="rememberMe" ng-click="rememberMe1();" type="checkbox"> Remember me
</label>
<div class="modal-footer">
<div>
<button type="submit" ng-click="submitLogin()" class="btn btn-primary btn-lg btn-block">Login</button>
</div>
<div>
my angular controller:
$scope.loginDetails = {
"email": "",
"username": "",
"password": "",
};
};
$scope.rememberMe1 = function () {
$cookies.put("emailId", $scope.loginDetails.email);
};
$scope.submitLogin = function () {
var emailId = $cookies.get("emailId"); ``
$scope.loginDetails.email = emailId;
})
}); ``
};
i believe that you'r code have so many errors and it will not even run try console.log()
solution with local storage
first in you'r service's file add Ls service
App.factory("LS", function($window, $rootScope) {
return {
setData: function (key , val) {
$window.localStorage && $window.localStorage.setItem(key , val);
return this;
},
getData: function (key) {
return $window.localStorage && $window.localStorage.getItem(key);
}
};
});
in you'r file login.js add this code
add service LS
var myMail = LS.getData('emailId');
$scope.loginDetails={
"email":"",
"username":"",
"password":""
};
$scope.rememberMe1 = function () {
LS.setData("emailId", $scope.loginDetails.email);
};
$scope.submitLogin=function(){
$scope.loginDetails.email = myMail;
};
Related
This question already has answers here:
Why are Callbacks from Promise `.then` Methods an Anti-Pattern
(2 answers)
Closed 5 years ago.
I am adding a simple todo list to my ionic vs1/angularjs project.
I want to use the ionic modal to launch this list. Since I need to launch it from everywhere I looked for a way to do this.
I found this article https://medium.com/#saniyusuf/create-an-isolate-modal-with-ionic-v1-b4cf73f05727 which had me create a factory that could be launched from any controller. Love it!
Problem is, it's a todo list where users need to be able to add/delete.
I want to save this information to firebase so I created a factory to hold all the firebase crud operations for the ToDo list.
So I now have a factory that launches the modal and one that has the firebase crud operations.
In the modal launcher I figured out how to include the crud operations so that the buttons would interact. Problem is how do I get the value of the input.
Modal Launcher
angular.module('formulaWizard')
.factory('IsolateModal', IsolateModal)
IsolateModal.$inject = ['$rootScope', '$ionicModal', '__ToDo',
'$window'];
function IsolateModal($rootScope, $ionicModal, __ToDo, $window) {
var modalsIsolateScope = $rootScope.$new();
var currentUser = $rootScope.currentUser || JSON.parse($window.sessionStorage.getItem('payload'));
var isolateModal = {
open: open
};
function open() {
$ionicModal.fromTemplateUrl(
'app/to-do/toDo.html',
{
scope: modalsIsolateScope
}
)
.then(function (modalInstance) {
modalsIsolateScope.close = function () {
closeAndRemove(modalInstance);
},
modalsIsolateScope.add = function(){
addTodo(modalInstance);
};
return modalInstance.show();
});
}
function closeAndRemove(modalInstance) {
return modalInstance.hide()
.then(function () {
return modalInstance.remove();
});
}
function addTodo(modalInstance) {
var i = modalInstance
__ToDo.toDo($scope.input)
.then(function(result) {
$scope.input = {};
// Reload our todos, not super cool
getAllTodos();
});
}
return isolateModal;
}
My Data Factory
angular.module('formulaWizard')
.factory('__ToDo', function(__Refs, $q) {
return {
toDo: function(id, userObject, cb) {
var toDo = __Refs.userNotes.child(id).push(userObject);
__Refs.userNotes.child(id).child(newToDo.key()).update({ toDo_id:
newToDo.key() }).then(function(response) {
cb(response);
}, function(e) {
console.error('error occured');
});;
},
updateToDo: function(userId, toDoId, userObject, cb) {
var x =
__Refs.userNotes.child(userId).child(toDoId).update(userObject)
.then(function(response) {
cb(response);
}, function(e) {
console.error('Error editing');
});
},
deleteToDo: function(userId, toDoId, cb) {
__Refs.userNotes.child(userId).child(toDoId).remove(function(error) {
if (error) {
console.error(error);
} else {
cb();
}
});
},
getuserNotes: function(id, cb) {
__Refs.userNotes.child(id).on('value', function(response) {
cb(response.val());
});
}
}
});
Call From Controller
$scope.openModal = function () {
IsolateModal.open();
};
Html
<ion-modal-view>
<ion-header-bar class="bar-stable">
<h1 class="title">My List</h1>
<button class="button icon ion-close-round button-icon"
ng-click="close()"></button>
</ion-header-bar>
<ion-content>
<div class="list card" style="width:100%; margin-left:0;">
<div class="item item-body">
<div class="item-input-inset">
<label class="item-input-wrapper">
<input id="newInput" type="text" placeholder="New Todo"
ng-model="input.name">
</label>
<button class="button button-balanced button-small" ng-click="add()">
Add Todo
</button>
</div>
<ion-list can-swipe="true">
<ion-item ng-repeat="item in todos">
{{item.name}}
<ion-option-button class="button-assertive" ng-click="deleteTodo(item.id)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</div>
</div>
</ion-content>
</ion-modal-view>
How can I get the input value from the html page into the factory?
Thanks
how do I get the value of the input?
Return the promise:
function open() {
̲r̲e̲t̲u̲r̲n̲ $ionicModal.fromTemplateUrl(
'app/to-do/toDo.html',
{
scope: modalsIsolateScope
}
)
.then(function (modalInstance) {
modalsIsolateScope.close = function () {
closeAndRemove(modalInstance);
},
modalsIsolateScope.add = function(){
addTodo(modalInstance);
};
return modalInstance.show();
});
}
Then extract the returned value from the promise:
$scope.openModal = function () {
var promise = IsolateModal.open();
promise.then(function(value) {
console.log(value);
});
return promise;
};
I am having difficulties combining both the editing of a current contact and the creation of a new contact. I am able to edit the contact that I click on, however, when I try and click on add new address the following error message -
angular.js:13424 Error: [$injector:unpr] http://errors.angularjs.org/1.5.3/$injector/unpr?p0=editIndexProvider%20%3C-%20editIndex%20%3C-%20ModalCtrl
This is due to using resolve based on the answer here
Factory
'use strict';
var app = angular.module('testApp', ['ngRoute','ui.bootstrap']);
app.factory('addressFactory', function(){
var addressFactory = {};
addressFactory.addressBook = [];
addressFactory.saveAddress = function(name, address){
addressFactory.addressBook.push({
name: name,
address: address
});
};
addressFactory.updateAddress = function(name, address, index){
addressFactory.addressBook[index] = {
name: name,
address: address
};
};
return addressFactory;
})
CONTROLLERS
.app.controller('testCtrl', ['$uibModal', 'addressFactory', function ($uibModal, addressFactory) {
var testCtrl = this;
this.addressBook = addressFactory.addressBook;
this.open = function () {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/add-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl'
});
}
this.openEdit = function(index) {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/edit-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl',
resolve: {
editIndex: function () {
return index;
}
}
});
}
}])
.controller('ModalCtrl', ['$uibModalInstance','addressFactory','editIndex', function ($uibModalInstance,addressFactory, editIndex) {
this.addressBook = addressFactory.addressBook;
this.saveAddress = function( name, address) {
addressFactory.saveAddress( name, address);
$uibModalInstance.dismiss('cancel');
}
this.getIndex = editIndex;
console.log(this.getIndex)
this.updateAddress = function(name, address, index) {
addressFactory.updateAddress( name, address, index);
}
this.cancelAddress = function () {
$uibModalInstance.dismiss('cancel');
};
}]);
HTML
home.html
<a ng-click="ctrl.open()">Enter new address</a>
<div ng-repeat="contact in ctrl.addressBook track by $index">
<p class="contactName">{{contact.name}}</p>
<p class="contactAddress">{{contact.address}}</p>
<button ng-click="ctrl.openEdit($index)">Edit Contact</button>
</div>
form.html
<form>
<input ng-model="ctrl.name" type="text">
<input ng-model="ctrl.address" type="text">
</form>
edit-address.html
<h3>Edit address</h3>
<div ng-include="'app/views/partials/form.html'"></div>
<div>
<button ng-click="ctrl.cancelAddress()">Cancel</button>
<button ng-click="ctrl.updateAddress(ctrl.name, ctrl.address, ctrl.getIndex)">Save</button>
</div>
add-address.html
<h3>Add address</h3>
<div ng-include="'app/views/partials/form.html'"></div>
<div>
<button ng-click="ctrl.cancelAddress()">Cancel</button>
<button ng-click="ctrl.addAddress(ctrl.name, ctrl.address)">Save</button>
</div>
You use the same ModalCtrl for both the open and the openEdit function. The open function does not have a resolve parameter. This way, angular cannot resolve the injected editIndex. Try this:
this.open = function () {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/add-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl',
resolve: {
editIndex: function () {
return undefined;
}
}
});
}
I think you simply miss a module dependency to angular.ui.bootstrap...
At the moment I have javascript that allows all users from the (_User) table to log in. I have set up a Role called (Admins) within the role table and assigned one user to this role. Would this be an if statement?
At the moment this is how the user logs in successfully
$scope.logIn = function(form) {
Parse.User.logIn(form.username, form.password, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
window.location.href = "TEST.html";
},
It's easy to check whether any user belongs to a role. The only tricky part is to realize that the check includes a query, and is therefore an asynchronous operation. So first, a general purpose role checking function:
function userHasRole(user, roleName) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", roleName);
query.equalTo("users", user);
return query.find().then(function(roles) {
return roles.length > 0;
});
}
This returns a promise that will be fulfilled with a boolean, so you can call it like this:
var currentUser = Parse.User.current();
// is the user an "admin"?
userHasRole(currentUser, "admin").then(function(isAdmin) {
console.log((isAdmin)? "user is admin" : "user is not admin");
});
Apply it like this in your code. In the view:
<form role="form" name="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" ng-model="user.username" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" ng-model="user.password" />
</div>
<div class="form-group">
<button class="btn btn-ar btn-primary" ng-click="pressedLogIn()">Log in</button>
</div>
</form>
And in the controller:
(function() {
'use strict';
angular.module('myApp.controllers').controller('LogInController', LogInController);
LogInController.$inject = ['$scope'];
function LogInController($scope) {
$scope.user = { username:"", password:""};
function userHasRole(user, roleName) {
// defined exactly as above
// my real app has a user service, and this would be better placed there
}
$scope.pressedLogIn = function() {
if ($scope.loginForm.$valid) {
Parse.User.logIn($scope.user.username, $scope.user.password).then(function(user) {
$scope.user = user;
return userHasRole(user, "administrator");
}).then(function(isAdmin) {
alert("user is admin = " + isAdmin);
}, function(e) {
alert(error.message);
});
}
};
}
})();
I've installed angular-promise-tracker and I think I'm close to getting it working. The problem I'm having is that the "loading" text isn't showing. The data is fetched and does show when outputting it to the console.
So it appears that ng-show="loadingTracker.active()" isn't working. I can't see what I'm doing wrong with this.
Any help with this would be sincerely appreciated - as always :)
Here's my code:
HTML
<button ng-controller="weatherCtrl"
ng-model="hotel"
class="btn btn-default"
ng-click="loadWeather(hotel, $index)">
{{buttonText}} more</button>
<div collapse="isCollapsed">
<div class="well well-lg more-detail">
{{hotel.Description}}
<br /><br />
<div>
<div class="my-super-awesome-loading-box"
ng-show="loadingTracker.active()">
Loading..
</div>
</div>
</div>
</div>
JS
.controller('weatherCtrl', function ($scope, weather, $timeout, promiseTracker){
$scope.loadingTracker = promiseTracker();
$scope.buttonText= 'Load'
$scope.loadedHotelDetails=[];
$scope.loadWeather = function(hotel, index) {
// console.log('loadWeather')
weather.get({tracker: $scope.loadingTracker}, function (data){
console.log(data)
$scope.loadedHotelDetails.push(index)
})
})
angular.module('weather', [])
.factory('weather', function($http) {
var weather = {};
weather.get = function(params, callback) {
$http.get('/php/weather.php', {params: {tracker: params.tracker, page: params.page}}).success(function(data) {
callback(data);
});
};
return weather;
});
I've never used this module, but from the examples on github, I think you're supposed to call it like this in weather:
weather.get = function(params, callback) {
$http.get('/php/weather.php', {tracker: params.tracker, page: params.page}).success(function(data) {
callback(data);
});
};
Got it sorted, this is the code I needed:
.factory('weather', function($http) {
var weather = {};
weather.get = function(params) {
return $http.get('/php/weather.php', {tracker: params.tracker, page: params.page});
};
return weather;
});
I'm wondering how to show a simple loader before data was loaded.
I'm using ng-grid-1.3.2
I'm googling but I didn't find any example.
Bye
like Maxim Shoustin suggested you can use the angularjs-spinner from Jim Lavin which uses (deprecated) Response Interceptors.
I think it's explained best here :
http://codingsmackdown.tv/blog/2013/04/20/using-response-interceptors-to-show-and-hide-a-loading-widget-redux/
In a nutshell, in his first solution, what you have to do for your ng-grid app is:
1) Add the loading gif to your html (for loading gif look here)
<div id="loadingWidget" class="row-fluid ui-corner-all" style="padding: 0 .7em;" loading-widget >
<div class="loadingContent">
<p>
<img alt="Loading Content" src="images/ajax-loader.gif" /> Loading
</p>
</div>
</div>
2) In your code as soon as you have declared your app level module add the Response Interceptors for http requests to the configuration block
var app = angular.module('myCoolGridApp', ['ngGrid']);
app.constant('_START_REQUEST_', '_START_REQUEST_');
app.constant('_END_REQUEST_', '_END_REQUEST_');
app.config(['$httpProvider', '_START_REQUEST_', '_END_REQUEST_', function ($httpProvider, _START_REQUEST_, _END_REQUEST_) {
var $http,
interceptor = /* see extra details on codingsmackdown.tv */
$httpProvider.responseInterceptors.push(interceptor);
}
3) and then add your loadingWidget directive
app.directive('loadingWidget', ['_START_REQUEST_', '_END_REQUEST_', function (_START_REQUEST_, _END_REQUEST_) {
return {
restrict: "A",
link: function (scope, element) {
element.hide();
scope.$on(_START_REQUEST_, function () {element.show();});
scope.$on(_END_REQUEST_, function () {element.hide();});
}
};
}]);
See more details at codingsmackdown
I had the same question as you.
I find this nice tutorial about it: http://brianhann.com/ui-grid-the-easiest-customization-youll-ever-write/
He use vm.loading = true while fetching data from server and changed to false after complete.
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$http', '$timeout', function ($http, $timeout) {
var vm = this;
vm.reset = reset;
vm.noData = noData;
vm.gridOptions = {
columnDefs: [
{ field: 'name' },
{ field: 'age' }
]
};
reset();
////////////
// Initialize our data source
function init() {
$http.get('data.json')
.success(function (data) {
vm.gridOptions.data = data;
})
.finally(function () {
vm.loading = false;
});
}
// Reset the data source in a timeout so we can see the loading message
function reset() {
vm.loading = true;
vm.gridOptions.data = [];
$timeout(function () {
init();
}, 1000);
}
function noData() {
vm.gridOptions.data = [];
}
}]);
In the HTML, he uses ng-hide to show/hide the spinner based on values of gridOptions.data and vm.loading:
<div id="grid1" ui-grid="vm.gridOptions" class="grid">
<div class="grid-msg-overlay" ng-hide="!vm.loading">
<div class="msg">
<span>
Loading Data...
<i class="fa fa-spinner fa-spin"></i>
</span>
</div>
</div>
<div class="grid-msg-overlay" ng-hide="vm.loading || vm.gridOptions.data.length">
<div class="msg">
<span>No Data</span>
</div>
</div>
</div>
Here is the Plunker of the final version shown.
You have angularjs-spinner, see GitHub sources
I also needed a similar behavior and I came across this answer but I needed to show something inside the grid itself so here is something I put together. My idea is that I change the gridOptions on the fly and show a loader as a row inside the grid.
loaderOptions = {
"columnDefs": [{
"name": "",
"field": "loading",
"enableColumnMenu": false,
"cellTemplate": '<div style="width:90px; margin:auto;"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading...</div>'
}],
"data": [{
"loading": ""
}]
};
Simply,by adding this code in your html part:
<img alt="loading..." src='images/ajax-loader.gif")' /> loading message...
and the following code in your app.controller script:
$http.get(yourdataUrl)
.then(function (response) {
$scope.records = response.data;
$("#loadingWidget").hide();
});
it works fine for me!
The HTML code-sample
<img ng-show="loading" src="~/img/loding.jpg" />
<div class="ngtyle" ng-grid="myGridView"></div>
The AngularJs code-sample
var app = angular.module('App', ['ngGrid']);
app.controller('MainCtrl', function ( $scope, myService ) {
$scope.loading = true;
myService.get().then( function ( response ) {
$scope.items = response.data;
})
.finally(function() {
$scope.loading = false;
});
$scope.myGridView = {
data: 'dataList',
columnDefs: 'myDisplayColumns'};
});