login form in angular.js - angularjs

I was trying to implement login form by authenticating the credentials from data stored in json file. But i'm getting error like only first case is working.It's just a demo application trying to learn the concepts:
this is my controller:
var app = angular.module('myApp', []);
app.controller("myCtrl",function($scope, $http)
{
$scope.check = function(){
var sample;
$http.get('roles.json').then(function(res)
{
sample = res.data;
console.log(sample);
angular.forEach(sample, function(val)
{
if($scope.uName===val.userName)
{
if($scope.password===val.password)
{
alert("sucess");
}
else
{
alert("failure");
}
}
else
{
alert("failure");
}
});
}); // end of http
};// end of function
});
data is loading properly but seems like some problem in logic.
data in json:
[
{"userName":"stud101","password":"stud1","role":"student"},
{"userName":"stud102","password":"stud2","role":"student"},
{"userName":"superlib","password":"lib1","role":"Librarian"}
]
I'm getting success only with first case, in rest other cases failure.

$http.get('roles.json').then(function(res){
sample = res.data;
console.log(sample);
var isMatched = false;
angular.forEach(sample, function(val)
{
if($scope.uName==val.userName && $scope.password==val.password)
{
isMatched = true;
return false; // To stop the foreach loop if username and password both are matched.
}
});
if(isMatched)
{
alert("success");
}
else
{
alert("failure");
}
});

angular.forEach($scope.messagepool, function(value, key) {
if(value.userName==$scope.uName && value.password==$scope.password){
alert('success');
}else{
alert('faluire');
}
});
Use this instead of your foreach . Hope this helps (y)

Related

AngularJS check object/array is empty

I've read many questions and answers, noone has helped me. I've this function:
var model = {};
var mediaReproductionApp = angular.module("mediaReproductionApp",["ui.event",'ngAnimate']);
mediaReproductionApp.run(function ($http) {
$http.get("movimenti_per_totem.json").success(function (data) {
model.items = data;
});
});
mediaReproductionApp.controller("MediaReproductionCtrl", function($scope, $http, $timeout) {
$scope.item = model;
$scope.playVideo = function(media) {
return media ? "../gallery/video/" + media : null;
}
$scope.reproductionCodeIsEmpty = function() {
return Object.keys($scope.item).length == 0;
}
$scope.endVideo = function() {
$timeout(function() {
$http.get("php/delete_record.php").success(function () {
$http.get("movimenti_per_totem.json").success(function (data) {
$scope.item.items = data;
});
});
if($scope.reproductionCodeIsEmpty()) {
prelevaDati('../json/52.json', 'spot_creator', 'sc1', modello_SC, {});
$scope.checkMediaData();
}
},1800);
}
$scope.checkMediaData = function() {
$http.get("movimenti_per_totem.json").success(function (data) {
$scope.item.items = data;
});
if($scope.reproductionCodeIsEmpty()) {
$timeout(function(){$scope.checkMediaData();},2000);
}
}
$scope.checkMediaData();
});
This is my JSON file when it is not empty:
[ {"media":"zafferano_VP8.webm"}, {"media":"amaretti_VP8.webm"}, {"media":"passata_VP8.webm"}]
It never return true when it is empty. I've tried also:
$scope.reproductionCodeIsEmpty = function() {
return $scope.item.length == 0;
}
$scope.reproductionCodeIsEmpty = function() {
return $scope.item == {};
}
$scope.reproductionCodeIsEmpty = function() {
return angular.isUndefined($scope.item) || $scope.item === null;
}
$scope.reproductionCodeIsEmpty = function() {
return angular.isUndefined($scope.item.items) || $scope.item.items === null;
}
Nothing works... can u tell me why?
Thank you!
After you added to your question:
You define model as: model.items = data;
So, you empty model is: model = { items: [] }.
That's why it isn't empty. You need to test for model.items being empty.
If you need a tested way to tell that the object is empty, I'd recommend lodash.isEmpty(). You can use it for "any Array-like values such as arguments objects, arrays, buffers, strings, or jQuery-like collections".
https://lodash.com/docs/4.15.0#isEmpty
Since I don't know what your model is, this would cover the most possible data types.
_.isEmpty(null);
// => true
_.isEmpty(true);
// => true
_.isEmpty(1);
// => true
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({ 'a': 1 });
// => false
If you want to check if object/array is empty, I use:
angular.equals({}, yourObject);
angular.equals([], yourArray);

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

error performing a get request

I am trying to perform a get request, in the post request everything is OK, I can see that in the post request all I do it's been save, once I refresh the page I am printing in the console the items saved by the post request, but those items aren't been return with the get I am doing.
here is where everything begins, I have a list of items here with the option to checked or unchecked the items in the list
<ion-item ng-repeat="sport in sports" ng-click="toggleSportSelection(sport)">
{{:: sport.name}}
</ion-item>
all the items are checked = true by default, so what I am saving, are the items with checked = false, the items checked = true you can see them here
<div ng-show="sport.checked" ng-repeat="sport in sports">
{{sport.name}}
</div>
this is what I have in the controller
.controller('SportsController', function($scope, SportsFactory) {
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sport, 'id'),
intersectedSports = _.intersection(sport.id, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}, function(err) {
console.log(err);
});
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
// this is what puts the sports on checked = true
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
and this is the service / factory
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
});
I am working along with NodeJS, so if you want the code I have in that part just let me know, so far I think that the issue I have is in the front end part, in the controller.

Uploading images to Firebase with AngularJS

I have a service that handles "episodes": creating, deleting and updating them. It looks like this:
app.service('Episode', ['$firebase', 'FIREBASE_URL', function($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var episodes = $firebase(ref);
return {
all: episodes,
create: function(episode) {
location.reload();
//Add to firebase db
return episodes.$add(episode);
},
delete: function(episodeId) {
location.reload();
return episodes.$remove(episodeId);
},
update: function(episode) {
location.reload();
return episodes.$save(episode);
}
};
}]);
Inside my controller:
app.controller('AdminCtrl', ['$scope', 'Episode', function ($scope, Episode) {
$scope.episodes = Episode.all;
$scope.createEpisode = function(){
Episode.create($scope.episode).then(function(data){
$scope.episode.name = '';
$scope.episode.title = '';
$scope.episode.description = '';
$scope.episode.time = '';
$scope.episode.img = '';
});
};
$scope.deleteEpisode = function(episodeId){
if(confirm('Are you sure you want to delete this episode?') === true) {
Episode.delete(episodeId).then(function(data){
console.log('Episode successfully deleted!');
});
}
};
$scope.updateEpisode = function(episode) {
Episode.update($scope.episode).then(function(data) {
console.log('Episode successfully updated.');
});
};
The only example of uploading images to Firebase from AngularJS I've seen online is this: https://github.com/firebase/firepano
How am I able to incorporate this into an object based addition/update instead of finding it's index/link?

Resources