angular directive auth all the logic in the service - angularjs

I should manage a directive for a login
form because of append a msg just in case
the credentials are wrong so I end up with:
HTML
<form role="form" name="form" data-auth="" data-ng-submit="getAuth()" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" name="email" placeholder="Email address" required="required" autofocus="autofocus" data-ng-model="user.email" class="form-control">
<input type="password" name="password" placeholder="Password" required="required" data-ng-model="user.password" class="form-control">
<label class="checkbox">
<input type="checkbox" value="remember-me">Remember me
</label>
<input type="submit" value="Sign in" data-ng-disabled="form.$invalid" class="btn btn-lg btn-primary btn-block">
</form>
JS
.factory('Auth', function($http,$q,$window) {
return {
send : function(data){
var deferred = $q.defer();
$http.post('/user/auth',data)
.success(function (response) {
deferred.resolve(response);
})
.error(function(data, status, headers, config) {
deferred.reject([]);
});
return deferred.promise;
},
authenticate:function(data){
}
}
})
.controller('MainCtrl', function ($scope,Auth) {
$scope.user = {};
})
.directive('auth',function($window,Auth) {
return {
restrict: 'A',
controller: function($scope,$element) {
$scope.getAuth = function(){
Auth.send($scope.user).then(
function(response){
if( (typeof response.data !== 'undefined') && (response.data === $scope.user.email)){
$window.location.href = 'http://localhost:3000/admin';
}
},
function(reject){
$('#invalid-login').remove();
$element.prepend('<p id="invalid-login" class="text-danger text-center">Invalid login</p>');
}
);
};
}
};
});
I'd like to put all the logic in the service
but I don't find the way ^^
EDIT
.factory('Auth', function($http,$q,$window) {
return {
send : function(data){
var deferred = $q.defer();
$http.post('/user/auth',data)
.success(function (response) {
deferred.resolve(response);
})
.error(function(data, status, headers, config) {
deferred.reject([]);
});
return deferred.promise;
},
authenticate:function(data,callBackOnError){
this.send(data).then(
function(response){
if( (typeof response.data !== 'undefined') && (response.data === data.email)){
$window.location.href = 'http://localhost:3000/admin';
}
},
callBackOnError
);
}
}
})
.controller('MainCtrl', function ($scope,Auth) {
$scope.user = {};
})
.directive('auth',function($window,Auth) {
return {
restrict: 'A',
controller: function($scope,$element) {
$scope.getAuth = function(){
Auth.authenticate(
$scope.user,
function(reject){
$('#invalid-login').remove();
$element.prepend('<p id="invalid-login" class="text-danger text-center">Invalid login</p>');
}
);
};
}
};
});
not so bad ^^

Change your HTML such that your call to getAuth has the user as parameter
<form role="form" name="form" data-auth="" data-ng-submit="getAuth(user)" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" name="email" placeholder="Email address" required="required" autofocus="autofocus" data-ng-model="user.email" class="form-control">
<input type="password" name="password" placeholder="Password" required="required" data-ng-model="user.password" class="form-control">
<label class="checkbox">
<input type="checkbox" value="remember-me">Remember me
</label>
<input type="submit" value="Sign in" data-ng-disabled="form.$invalid" class="btn btn-lg btn-primary btn-block">
Change your service such that it includes the getAuth function:
.factory('Auth', function($http,$q,$window) {
return {
send : function(data){
var deferred = $q.defer();
$http.post('/user/auth',data)
.success(function (response) {
deferred.resolve(response);
})
.error(function(data, status, headers, config) {
deferred.reject([]);
});
return deferred.promise;
},
authenticate:function(data){
},
getAuth: function(user){
send(user).then(
function(response){
if( (typeof response.data !== 'undefined') && (response.data === $scope.user.email)){
$window.location.href = 'http://localhost:3000/admin';
}
},
function(reject){
$('#invalid-login').remove();
$element.prepend('<p id="invalid-login" class="text-danger text-center">Invalid login</p>');
}
);
}
}
})
And finally change the controller like that:
.controller('MainCtrl', function ($scope,Auth) {
$scope.user = {};
$scope.getAuth = Auth.getAuth;
})

Related

Angular contact form - undefined field after after sending

Here is my index.html
<div data-ng-controller="help">
<div id="messages" class="alert alert-success" data-ng-show="messages" data-ng-bind="messages"></div>
<div data-ng-show="progress.active()" style="color: red; font-size: 50px;">Sending…</div>
<form name="helpForm" novalidate role="form">
<div class="form-group">
<label for="name">Your Name </label>
<span class="label label-danger" data-ng-show="submitted && helpForm.name.$error.required">Required!</span>
<input type="text" name="name" data-ng-model="userName" class="form-control" required />
</div>
<div class="form-group">
<label for="email">Your E-mail address</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.email.$error.required">Required!</span>
<span class="label label-danger" data-ng-show="submitted && helpForm.$error.email">Invalid email!</span>
<input type="email" name="email" data-ng-model="userEmail" class="form-control" required />
</div>
<div class="form-group">
<label for="message">Message</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.message.$error.required">Required!</span>
<textarea name="message" data-ng-model="userMessage" class="form-control" required></textarea>
</div>
<button data-ng-disabled="progress.active()" data-ng-click="submit(helpForm)" class="btn btn-default">Submit</button>
</form>
And part of my app.js
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.subjectListOptions = {
'bug': 'Report a Bug',
'account': 'Account Problems',
'mobile': 'Mobile',
'user': 'Report a Malicious User',
'other': 'Other'
};
$scope.progress = promiseTracker();
$scope.submit = function(form) {
$scope.submitted = true;
if (form.$invalid) {
return;
}
var $promise = $http({
method: 'POST',
url:'api/contactUs',
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
})
.success(function(data, status, headers) {
if (data.status == 'OK') {
$scope.userName = null;
$scope.userEmail = null;
$scope.userMessage = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
})
.finally(function() {
$timeout(function() {
$scope.messages = null;
}, 9000);
});
After sending the letter to mail, all fields (name, email, message) in the form are displayed as "Undefined"
I use an node.js server and connect via api (api/contactUs)
I can not understand what the problem is, already tried everything I could, but the error remains.
Please help with the solution of this problem.
Thank you in advance!
When you use POST method, you should pass data object instead of params object.
Change this:
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
To this:
data: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}

Angular js:Not able to get the response for the rest method

I am trying to create a simple login form using angular js and rest webservice.
I am able to call the rest webservice, but not able to get the response.
1)Login form:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<div class="alert alert-danger">Error</div>
<form name="form" role="form" method="post" data-ng-submit="login(credentials)"
data-ng-controller="LoginController">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" data-ng-model="credentials.username" required />
<span class="help-block">Username is required</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" data-ng-model="credentials.password" required />
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Login</button>
<img src="img/ajax-loader-blue.gif" />
Register
</div>
</form>
</div>
2)Restwebservice
#Path("/login")
public class LoginRestfulService {
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Users getUserProfile(CredentialInBean credentials) {
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+" credentials: "+credentials.getUsername()+""+credentials.getPassword());
UserService userService = new UserService();
return userService.getUserProfile(credentials);
}
}
3)
public Users getUserProfile(CredentialInBean credentials) {
if(credentials!=null && credentials.getUsername().equals("Firstname")){
Users user = new Users();
user.setFirstName("Firstname");
user.setLastName("lastname");
return user;
}
return null;
}
4)LoginController
app.controller('LoginController', function($scope, $rootScope, AUTH_EVENTS,
AuthService) {
$scope.credentials = {
username : '',
password : ''
};
$scope.login = function(credentials) {
AuthService.login(credentials).then(function(user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.currentUser = null;
$scope.setCurrentUser = function(user) {
$scope.currentUser = user;
};
}, function() {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
})
5)AuthService
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response = { success: true };
} else {
response = { success: false, message: 'Username or password is incorrect' };
}
alert(response.data);
return response.data;
});
};
});
Here respose.data comes as undefined.
Can any one help me to solve the issue?
you can't override the response here.
For the best you can add more attributes to this object like:
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response.success = true ;
} else {
response = {};
response.success = false;
response.message = 'Username or password is incorrect';
}
alert(response.data);//you will preserve the data
return response.data;//won't be undefined
});
};
});

AngularJs and Controller alias

I tried to alias the AngularJS controller in the view, but for some strange reason - it does not seem to respond when I prefix the methods and properties - any idea what might be causing it?
Here's my view (I'm using it with Laravel 5.1):
#extends('admin.template.layout-login')
#section('content')
<div class="row">
<div class="large-6 medium-8 columns large-offset-3 medium-offset-2" ng-controller="LoginController as login">
<form
name="htmlForm"
class="panel hide"
ng-submit="login.submit()"
ng-class="{ 'show-block' : !login.isRequestCompleted() }"
novalidate
>
<label for="username">
Username: *
<ng-messages
for="htmlForm.username.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your email address</ng-message>
<ng-message
when="email"
class="warning"
>Invalid email address</ng-message>
<ng-message
when="unsuccessful"
class="warning"
>Incorrect login details</ng-message>
<ng-message
when="suspended"
class="warning"
>Your account has been suspended</ng-message>
</ng-messages>
</label>
<input
type="email"
ng-model="formData.username"
name="username"
id="username"
required
>
<label for="password">
Password: *
<ng-messages
for="htmlForm.password.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your password</ng-message>
<ng-message
when="password"
class="warning"
>Invalid password</ng-message>
</ng-messages>
</label>
<input
type="password"
ng-model="formData.password"
name="password"
id="password"
required
password
>
<label for="remember">
<input
type="checkbox"
ng-model="formData.remember"
name="remember"
id="remember"
> Remember Me
</label>
<input
type="submit"
class="small button"
value="SEND ENQUIRY"
ng-if="!login.isOutForDelivery()"
>
<button
type="button"
class="small button"
disabled
ng-if="login.isOutForDelivery()"
>
PLEASE WAIT <i class="fa fa-spinner fa-spin"></i>
</button>
</form>
<div
class="hide"
ng-class="{ 'show-block' : login.isRequestCompleted() }"
ng-bind-html="login.trustAsHtml(confirmation)"
></div>
</div>
</div>
#endsection
and here's the AngularJS controller module:
(function(window, angular, app) {
"use strict";
app.controller(
'LoginController',
[
'$scope',
'$controller',
'$window',
function(
$scope,
$controller,
$window
) {
angular.extend(this, $controller('FormController', { $scope: $scope }));
$scope.submit = function() {
if ( ! $scope.isValid()) return false;
$scope.data = {
username : $scope.formData.username,
password : $scope.formData.password
};
$scope.submitRequest(
'/admin',
$scope.data
)
.success(function(data, status, headers, config, statusText) {
$window.location.href = data.url;
})
.error(function(data, status, headers, config, statusText) {
$scope.validation(data);
$scope.endOutForDelivery();
return false;
});
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
Plus the FormController that the previous extends:
(function(window, angular, app) {
"use strict";
app.controller(
'FormController',
[
'$scope',
'RequestService',
'ContentService',
function(
$scope,
RequestService,
ContentService
) {
$scope.outForDelivery = false;
$scope.requestCompleted = false;
$scope.submitRequest = function(url, formData) {
$scope.outForDelivery = true;
return RequestService.post(url, formData);
};
$scope.responseReceived = function() {
$scope.requestCompleted = true;
$scope.outForDelivery = false;
};
$scope.isResponseReceived = function() {
return $scope.requestCompleted && ! $scope.outForDelivery;
};
$scope.endOutForDelivery = function() {
$scope.outForDelivery = false;
};
$scope.trustAsHtml = ContentService.trustAsHtml;
$scope.isValid = function() {
return $scope.htmlForm.$valid;
};
$scope.isSubmitted = function() {
return $scope.htmlForm.$submitted &&
! $scope.isRequestCompleted();
};
$scope.isRequestCompleted = function() {
return $scope.requestCompleted;
};
$scope.isOutForDelivery = function() {
return $scope.outForDelivery;
};
$scope.validation = function(data) {
angular.forEach(data, function(value, key) {
this[key].$error[value] = true;
}, $scope.htmlForm);
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
None of the methods are on the controller. They're all defined on the $scope. So you can't access them using the login alias, which refers to the controller, not to the scope.
If you want to be able to call
login.foo()
from the view, then the method must be set on the controller, not on the scope:
this.foo = function() { ... };

CheckBox function for same ss billing sddress

i know its very common and very easy thing but really i m very new to angularjs and need your help
My View Page:
<div ng-controller="AddressController">
<div class="form-part-title" ng-show="Caption">{{Caption}} <span ng-show="showSameAsBilling" class="spancheck"><input type="checkbox" id="SameAsBilling" ng-model="Address.SameAsBilling"><label class=" after">Same As Billing Address</label></span> </div>
<div ng-show="!readOnly">
<label class="required">#Resource.Country<span ng-show="showInvalidAddress" class="spancheck"><input type="checkbox" id="InvalidAddress" ng-model="Address.InvalidAddress"><label class="after">Invalid Address</label></span>
<span ng-show="showPostalOnly" class="spancheck"><input type="checkbox" id="PostalOnly" ng-model="Address.PostalOnly"><label class="after">Postal Only</label></span>
</label>
<select kendo-drop-down-list class="sdk-dropdown" ng-model="Address.CountryId" k-options="countries" k-on-change="onChange(kendoEvent)" />
<label>#Resource.Address</label>
<input class="block" type="text" name="Address" ng-model="Address.Address1" maxlength="100" />
<input class="block" type="text" ng-model="Address.Address2" maxlength="100" />
<input class="block" type="text" ng-model="Address.Address3" maxlength="100" />
<label id="lblState">{{StateLabel}}</label>
<select kendo-drop-down-list class="sdk-dropdown" ng-model="Address.StateProvinceId" k-options="states" k-rebind="states" />
<label>#Resource.City</label>
<input class="block" type="text" name="City" ng-model="Address.City" maxlength="50" />
<label>{{ZipCodeLabel}}</label>
<input class="block" type="text" name="ZipCode" ng-model="Address.ZipCode" maxlength="50" />
</div>
<div ng-show="readOnly">
<textarea style="min-height:120px!important" disabled>{{Address.Address}}{{Address.Address1}}
{{Address.Address2}}
{{Address.City}}
{{Address.State}}{{Address.CountryName}}
{{Address.ZipCode}}</textarea>
</div>
</div>
My Angular Controller:
var AddressController = function ($scope, $http, $routeParams, $location) {
$scope.StateLabel = "State";
$scope.ZipCodeLabel = "Zip Code";
$scope.countryDataSource = {
transport: {
read: {
dataType: "json",
url: "/ApplicationData/GetCountries",
}
}
};
$scope.countries = {
dataSource: $scope.countryDataSource,
dataTextField: "Name",
dataValueField: "Id",
optionLabel: "Select..."
};
this.showAlert = function () {
alert("this is test method");
};
$scope.onChange = function (e) {
var countryId = e.sender.value();
if (countryId == 2) {
$scope.StateLabel = "Province";
$scope.ZipCodeLabel = "Postal Code";
}
else {
$scope.StateLabel = "State";
$scope.ZipCodeLabel = "Zip Code";
}
$http.get('/ApplicationData/GetStates/' + countryId).
success(function (jsonData, status, headers, config) {
console.log(jsonData);
var data = {
dataSource: jsonData,
dataTextField: "Name",
dataValueField: "Id",
optionLabel: "Select..."
};
$scope.states = data;
}).
error(function (data, status, headers, config) {
console.log("error getting countries");
});
};
$scope.SameAsBilling = function (checked) {
alert(1);
if (SameAsBilling.checked = true) {
vmCustomer.BillingAddress = vmCustomer.ShippingAddress
}
};
};
AddressController.$inject = ['$scope', '$http', '$routeParams', '$location'];
i need you guys to help me with the below function
$scope.SameAsBilling = function (checked) {
alert(1);
if (SameAsBilling.checked = true) {
vmCustomer.BillingAddress = vmCustomer.ShippingAddress
}
};
i m tying but don't know why the check box is not talking to controller please help

TypeError: undefined is not a function (AngularJS)

I'm struggling with a webshop I'm making in AngularJS. I'm trying to save a product into a database, but something goes wrong when I try to call a certain function. I'm getting this error:
TypeError: undefined is not a function
at l.$scope.createProduct (http://localhost:3000/controllers/product.Controller.js:30:20)
at hb.functionCall (http://localhost:3000/node_modules/angular/angular.min.js:198:426)
at Cc.(anonymous function).compile.d.on.f (http://localhost:3000/node_modules/angular/angular.min.js:215:74)
at l.$get.l.$eval (http://localhost:3000/node_modules/angular/angular.min.js:126:193)
at l.$get.l.$apply (http://localhost:3000/node_modules/angular/angular.min.js:126:419)
at HTMLFormElement.<anonymous> (http://localhost:3000/node_modules/angular/angular.min.js:215:126)
at HTMLFormElement.c (http://localhost:3000/node_modules/angular/angular.min.js:32:363)
I don't understand why this is happening, so I hope someone out there can help me. Here's my HTML code
<form ng-submit="createProduct()">
<div class="form-group">
<label for="id">ID</label>
<input type="text" ng-model="id" class="form-control" id="id" name="id" placeholder="Indtast det tilhørende ID">
</div>
<div class="form-group">
<label for="brand">Brand</label>
<input type="text" ng-model="brand" class="form-control" id="brand" name="brand" placeholder="Indtast brand">
</div>
<div class="form-group">
<label for="content">Indhold</label>
<input type="text" ng-model="content" class="form-control" id="content" name="content" placeholder="Indtast indhold">
</div>
<div class="form-group">
<label for="alcohol">Procent</label>
<input type="text" ng-model="alcohol" class="form-control" id="alcohol" name="alcohol" placeholder="Indtast antal procent">
</div>
<div class="form-group">
<label for="price">Pris</label>
<input type="text" ng-model="price" class="form-control" id="price" name="price" placeholder="Indtast prisen">
</div>
<div class="form-group">
<label for="category">Kategori</label>
<input type="text" ng-model="category" class="form-control" id="category" name="category" placeholder="Indtast kategori">
</div>
<button type="submit" class="btn btn-primary">Opret produkt</button>
</form>
Besides my HTML i also have a product.Controller and a products.service. The productController looks like this:
(function(){
function productController($scope, productsService, cartService, $routeParams){
var modelProduct = function(productArray){
$scope.product = productArray[0];
}
productsService.getProduct($routeParams.id)
.then(modelProduct);
$scope.addToCart = function(product, amount){
cartService.addToCart(product, amount);
}
$scope.createProduct = function() {
var product = {
id : this.id,
brand : this.brand,
content : this.content,
alcohol : this.alcohol,
price : this.price,
category : this.category
}
console.log(product);
productsService.saveProduct(product);
}
}
angular
.module("Main.product", [])
.controller("productController", productController);
})();
and my productsService looks like this:
(function(){
"use strict";
var productsService = function($http){
var categoriesSelected = new Array();
var products = new Array();
var getProducts = function(){
/* Hent fra den lokale grillbar
return $http.get("./data/products.json")
.then(function(response){
console.log(response.data);
return response.data;
}, getError);
/* Hent fra databasen */
return $http.get("api/products")
.then(function(response){
console.log(response.data);
return response.data;
}, getError);
};
var setProducts = function(data) {
products = data;
}
var getProduct = function(id) {
return $http.get("api/product/" + id)
.then(function(response) {
return response.data;
})
}
var saveProduct = function(product){
console.log(product);
return $http.post("api/product", product)
.then(function(response){
return response.data;
})
}
var getCategories = function(response){
return $http.get("./data/categories.json")
.then(function(response){
return response.data;
}, getError)
};
var getCategoriesSelected = function(){
return categoriesSelected;
}
var productFilter = function(product){
if(categoriesSelected.length > 0){
if(categoriesSelected.indexOf(product.category) < 0){
return;
}
}
return product;
}
var getError = function(reason){
console.log(reason);
}
var findProductInArray = function(data, prodId){
return data.filter(function(elem){
if(elem.prodId === prodId){
return elem;
}
});
}
var categoryChange = function(category){
var i = categoriesSelected.indexOf(category);
if (i > -1) {
categoriesSelected.splice(i, 1);
}
else {
categoriesSelected.push(category);
}
}
var categoryFilter = function(product) {
console.log("aks");
if($scope.categoriesSelected.length > 0) {
if($scope.categoriesSelected.indexOf(product.category) < 0) {
return;
}
}
return product;
}
return{
getProducts: getProducts,
getProduct: getProduct,
getCategories: getCategories,
getCategoriesSelected: getCategoriesSelected,
productFilter: productFilter,
categoryChange: categoryChange,
categoryFilter: categoryFilter
}
}
angular
.module("Main.products")
.factory('productsService', productsService);
})();
I hope someone out there can help me!
You don't appear to be exporting saveProduct as a public method of your service:
return{
getProducts: getProducts,
getProduct: getProduct,
getCategories: getCategories,
getCategoriesSelected: getCategoriesSelected,
productFilter: productFilter,
categoryChange: categoryChange,
categoryFilter: categoryFilter
}

Resources