I am making a test app on MEAN stack and whenever I try to update information in my database regarding the fields, Google chrome throws Connection refused to the Url where I am posting the stuff.
Code for the controller:
(function() {
angular.module('TimeSuck')
.controller('EditProfileController',['Upload','$scope','$state', '$http', function(Upload, $scope, $state, $http) {
$scope.user = localStorage['Userdata'] || undefined
$scope.$watch(function(){
return $scope.file
},function(){
$scope.upload($scope.file);
});
$scope.upload = function(file) {
if(file){
Upload.upload({
url:'api/profile/editPhoto',
method: 'POST',
data: {userId: $scope.user._id},
file: file
}).progress(function(event){
console.log("Uploaded");
}).success(function(data){
}).error(function(error){
console.log(error);
})
}
};
$scope.updateUsername = function() {
var request = {
userId: $scope.user[0]._id,
username: $scope.username
}
$http.post('api/profile/updateUsername', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
})
}
$scope.updateBio = function() {
var request = {
userId: $scope.user[0]._id,
bio: $scope.bio
}
$http.post('api/profile/updateBio', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
});
}
$scope.post = function() {
console.log("successfully Posted.");
}
and the code for the html is here:
<div class="jumbotron">
<div class="col-sm-8 col-sm-offset-2">
<div class="row"> <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
ngf-accept="'image/*'" >Select</div> </div>
<div class="row">
<input class="form-control" ng-model="username" ng-blur="updateUsername()">
</div>
<div class="row">
<textarea class="form-control" ng-model="Bio" ng-blur="updateBio()"> </textarea>
<button type="submit" ng-click="post()"> Post </button>
</div>
</div>
</div>
Related
I have a application running with a flask backend and angular frontend. Apparently when a wrong password is entered i want to show a error message. I have tried out ng-show and ng-if both nothing seems to work.
This is the html for my login page -
<div layout="column" layout-align="center center" class="">
<img class="logo" ng-src="assets/images/logo.png">
<h1 class="md-display-2 login-heading">Login to Bassa</h1>
<div layout="row">
<md-input-container>
<label>User name</label>
<input type="text" ng-model="user.user_name"/>
</md-input-container>
<md-input-container>
<label>Password</label>
<input type="password" ng-model="user.password" ng-enter="login()"/>
</md-input-container>
<br>
</div>
<div>
<md-button class="md-raised md-primary" ng-click="login()">Login</md-button>
<md-button class="md-raised md-primary" ng-click="signup()">Signup</md-button>
</div>
And this is the login controller -
(function(){
'use strict';
angular
.module('app')
.controller('LoginCtrl', ['$scope', '$state', 'UserService', LoginCtrl]);
function LoginCtrl($scope, $state, UserService) {
$scope.user = {};
$scope.incorrectCredentials = false;
$scope.login = function(){
UserService.login($scope.user, function(status) {
if (status){
$state.go('home.dashboard');
} else {
$scope.incorrectCredentials = true;
}
});
};
$scope.signup = function() {
$state.go('signup');
};
UserService.removeToken();
}
})();
When the incorrectCredentials becomes true , i want to show a message.
After logging the User service -
var login = function(credentials, cb) {
var $http = $injector.get('$http');
return $http({
method: 'POST',
url: BassaUrl + '/api/login',
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
setToken(response.headers()['token']);
setName(credentials.user_name);
setAuthLevel(response.data.auth);
console.log(response);
cb(true);
}, function(error){
console.log("hello i am here")
cb(false);
});
};
I received a response log -
Object {data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…ead-protected or not readable by the server.</p>↵", status: 403, config: Object, statusText: "FORBIDDEN"}
It isn't entering the error block , which prevents me from prompting wrong password message.
It was actually my own fault. My custom Interceptor simply swallowed authentication errors.
I created a common modal service in my application.
But it's not working somehow. Some small thing am missing on this plunker but am not able to figure out.
Based on passed parameter either it will open error-dialog or cancel-dialog.
Find PLUNKER here
Here is
JS
// create angular app
var validationApp = angular.module('validationApp', ['ui.bootstrap']);
// create angular controller
validationApp.controller('mainController', function($scope, ModalService) {
var vm = this;
// function to submit the form after all validation has occurred
vm.submitForm = function() {
// check to make sure the form is completely valid
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
};
function openDialog() {
alert('why am not showing');
ModalService.openModal('Analysis Error', 'Complete Application Group configuration prior to running analysis.', 'Error');
}
});
//controller fot dialog
validationApp.controller('ErrorDialogCtrl',
function($uibModalInstance, message, title, callback) {
alert('sfdsfds');
var vm = this;
vm.message = message;
vm.onOk = onOk;
vm.onContinue = onContinue;
vm.onDiscard = onDiscard;
vm.callback = callback;
vm.title = title;
function onOk() {
$uibModalInstance.close();
}
function onContinue() {
$uibModalInstance.close();
}
function onDiscard() {
vm.callback();
$uibModalInstance.close();
}
});
// common modal service
validationApp.service('ModalService',
function($uibModal) {
return {
openModal: openModal
};
function openErrorModal(title, message, callback) {
$uibModal.open({
templateUrl: 'ErrorDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openCancelModal(title, message, callback) {
$uibModal.open({
templateUrl: 'CancelDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openModal(title, message, modalType, callback) {
if (modalType === "Error") {
openErrorModal(title, message, callback);
} else {
openCancelModal(title, message, callback);
}
}
}
);
Opening Dialog in HTML
<div class="col-sm-6">
<button type="submit" class="btn btn-primary" ng-click="openCancelDialog()">Open Cancel Dialog</button>
<button type="submit" class="btn btn-primary" ng-click="openErrorDialog()">Open Error Dialog</button>
</div>
Cancel Dialog HTML
<div>
<div class="modal-header">
<h3 class="modal-title">{{vm.title}}</h3>
</div>
<div class="modal-body">
<p ng-bind-html="vm.message"></p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="vm.onContinue()" id="continue">Continue</button>
<button class="btn btn-primary" ng-click="vm.onDiscard()" id="discard">Discard</button>
</div>
</div>
ErrorDiaog HTML
<div>
<div class="modal-header">
<h3 class="modal-title">{{vm.title}}</h3>
</div>
<div class="modal-body">
<p ng-bind-html="vm.message"></p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="vm.onOk()">ok</button>
</div>
</div>
wrong in your js file, you need to declare function like below. you just copy these code and put it in your file then it will work fine.
NOTE: not ModalService.showModal, it should be ModalService.openModal
check your code here
$scope.openCancelDialog = function() {
alert('why am not showing CAncel');
ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');
}
$scope.openErrorDialog = function() {
console.log('why am not showing Error');
ModalService.openModal('Analysis Error', 'I am cancel Type', 'Cancel');
}
i've created a new PLNKR here:
https://plnkr.co/edit/3RBJneSt7RCClrJ5Hba2?p=preview
$scope.submitForm = function() {
//check to make sure the form is completely valid
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
};
$scope.openCancelDialog = function(){
//alert('why am not showing CAncel');
ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');
}
$scope.openErrorDialog = function(){
//alert('why am not showing Error');
ModalService.openModal('Analysis Error', 'I am cancel Type', 'Cancel');
}
I want to Refresh the page after displaying a message or alert saying "Successful" or vice-versa. How can I implement it?
I tried refresing code but it do not display message after that.
HTML CODE:
<div class="row" ng-controller="PublishManifestCtrl">
<div class="col-xs-12 col-md-12">
<div class="widget">
<div class="widget-header bordered-bottom bordered-themeprimary">
<i class="widget-icon fa fa-tasks themeprimary"></i>
<span class="widget-caption themeprimary">Manifest Status</span>
</div>
<div class="widget-body">
<form class="form-bordered" role="form">
<div class="form-group">
<label style="padding-left: 8px;">Manifest was last published to agents on <b>{{manifeststatus.manifestLastPublishedDate}}</b>.</label>
</div>
<div class="form-group">
<label style="padding-left: 8px;">Manifest was last updated by <b> {{manifeststatus.lastUpdatedByUser}} </b> on <b>{{manifeststatus.manifestLastedUpdatedDate}}</b>.</label>
</div>
<div class="form-group">
<div class="col-sm-offset-1">
<button id="PublishButton" class="btn btn-default shiny " ng-disabled="manifeststatus.enablePublishButton" ng-click="Save(manifeststatus)">Publish</button>
</div>
<br/>
<div id="statusDivPublish" ng-show="showstatus">
<alert type="{{alert.type}}">{{alert.msg}}</alert>
</div>
</div>
</form>
</div>
JS Code:
app.controller('PublishManifestCtrl', function ($scope, $rootScope, $http) {
$scope.showstatus = false;
$http({
url: $rootScope.WebApiURL + '/getmanifeststatus',
method:get(),
params: { 'foobar': new Date().getTime() }
}).
success(function (data, status, headers, config) {
var options = { year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric" };
data.manifestLastedUpdatedDate = (new Date(data.lastUpdatedDateTime)).toLocaleDateString('en-US', options);
data.manifestLastPublishedDate = (new Date(data.lastPublishDateTime)).toLocaleDateString('en-US', options);
var date1 = new Date(data.lastUpdatedDateTime);
var date2 = new Date(data.lastPublishDateTime);
data.enablePublishButton = date2.getTime() > date1.getTime();
$scope.manifeststatus = data;
}).
error(function (data, status, headers, config) {
alert('error' + status);
// log error
});
$scope.Save = function (data) {
debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//refresh
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
)});
Implementation
$scope.Save = function (data) {
// debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//made change
$scope.manifeststatus = data;
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
//refresh
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
}
});
Originally It should be in this way:
in your html
<div>{{date}}</div>
in our angularjs file
$scope.Save = function (data) {
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
$scope.date = data.date;
//refresh
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
$(".statusDivPublish").remove();
)});
I am trying to read and insert excel file data to mysql database table using angularjs( front and) and codeigniter (back end).thanks in advance
included xlsx-reader.js
this is only the excel file read code it is not working.
HTML
<div ng-app="App">
<div ng-controller="PreviewController">
<div class='form-group'>
<label for='excel_file'>Excel File</label>
<button class="btn btn-link" type="file" ng-model="file"ngf-select ngf-change="importToExcel()">
<span class="glyphicon glyphicon-share"></span>ImportExcel
</button>
</div>
</div>
</div>
app.js
(function(undefined) {
App.factory("XLSXReaderService", ['$q', '$rootScope',
function($q, $rootScope) {
var service = function(data) {
angular.extend(this, data);
};
service.readFile = function(file, showPreview) {
var deferred = $q.defer();
XLSXReader(file, showPreview, function(data){
$rootScope.$apply(function() {
deferred.resolve(data);
});
});
return deferred.promise;
};
return service;
}
]);
}).call(this);
controller.js
angular.module('App').controller('PreviewController', function($scope, XLSXReaderService)
{
$scope.showPreview = false;
$scope.importToExcel= function(files) {
$scope.sheets = [];
$scope.excelFile = file[0];
XLSXReaderService.readFile($scope.excelFile, $scope.showPreview).then(function(xlsxData) {
$scope.sheets = xlsxData.sheets;
});
};
}
I just want to asked if there's a better way to improve my user validation codes.
directive.js
angular.module('installApp')
.directive('usernameValidator', function ($q, $timeout, $http) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(modelValue, viewValue) {
return $http.post('../api/v1/checkUsers', {user: {'username':viewValue}}).then(
function(response){
scope.checkUsers = response.data;
var deferred = $q.defer();
$timeout(function() {
if(scope.checkUsers['status'] == 404){
deferred.reject();
}else{
deferred.resolve();
}
}, 2000);
return deferred.promise;
});
};
}
}
});
accounts.html
<form name="myForm" ng-submit="submit()">
<div>
<label>Username: <input type="text" ng-model="signup.username" name="username" required username-validator>
</label>
<div ng-if="myForm.username.$dirty">
<div ng-messages="myForm.username.$error" class="validation-error">
<div ng-message="required">Username required</div>
<div ng-message="username">Username already in use</div>
</div>
<div ng-messages="myForm.username.$pending" class="validation-pending">
<div ng-message="username">Checking username availability... </div>
</div>
</div>
</div>
<div>
<label>Password: <input type="password" ng-model="signup.password" name="password" required></label>
<div ng-messages="myForm.password.$error" ng-if="myForm.password.$dirty" class="validation-error">
<div ng-message="required">Password required</div>
</div>
</div>
<button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Submit</button>
</form>
The above code is perfectly working fine, but there is a doubt in my mind on how can I improve it in a better way. I've seen many examples and I noticed they didn't used mostly the if/ else condition. Please help
One thing you could do is try to make your directive reusable.
A good example I found on the internet is coming from Year of moo
angular
.module('yourmodule')
.directive('recordAvailabilityValidator',
['$http', function($http) {
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
var apiUrl = attrs.recordAvailabilityValidator;
function setAsLoading(bool) {
ngModel.$setValidity('recordLoading', !bool);
}
function setAsAvailable(bool) {
ngModel.$setValidity('recordAvailable', bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
setAsAvailable(false);
$http.get(apiUrl, { v : value })
.success(function() {
setAsLoading(false);
setAsAvailable(true);
})
.error(function() {
setAsLoading(false);
setAsAvailable(false);
});
return value;
})
}
}
}]);