ng-click event is not firing on button click? - angularjs

i'm creating web application in Angularjs i write code in separate .js file for log in from database
is is execute on page load but not triggering on button click,
my .js code is:
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
Login();
function Login(U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
}]);
and my view as what i'm using for binding this using Angularjs here is an issue above code is working on page load but don't work on button click, the code i use is:
<div class="admin-login" ng-controller="AdminCtrl" ng-app="angApp">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
anyone please help me what i miss here so i'm not able to trigger ng-click event on button click
thanks in advance.

Your Login function needs to be on a scope. Right now, its essentially a private function:
$scope.Login = function () {
...
}

assign function to a scope variable.
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.Login = function (U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
$scope.Login();
}]);
Edited:
try to use this html code,but i am not sure.it may be that both ng-init and ng-controller are in same div and ng-controller load first after that ng-init :
<div ng-app="angApp">
<div class="admin-login" ng-controller="AdminCtrl" >
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>

Related

Spinner Loading with AngularJS

I wanted to make Spinner should appear when user clicks on Submit Button and Spinner should stop once the AJAX POST and GET request completed
Can you Please help me know How I make my below Angular Code to implement the feature.
Below is the Example I saw for Spinner in Angular
Demo
Below is my AngularJS code .
var app = angular.module("myApp", ["ngTable"]);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'mainDeviceSite.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.cellularIPAddressValue = response.data.devices;
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'BEPEvents.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
var x2js = new X2JS();
$scope.aftCnv = x2js.xml_str2json(response.data);
$scope.bepValues = $scope.aftCnv.EEPEvents.BlobData;
console.log($scope.bepValues);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
HTML Code
<div class="example">
<div class="col-md-12">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction()" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{message}}</span>
</div>
</div>
</div>
</div>
Try Following solution
This applicable for all http request that are use in angular controller. When you call http request then spinner and progress bar you shows
Demo
Refer this angular-loading-bar.
include the loading bar as a dependency for your app. If you want animations, include ngAnimate as well. note: ngAnimate is optional
angular.module('myApp', ['angular-loading-bar', 'ngAnimate'])
include the supplied JS and CSS file (or create your own CSS to override defaults).
<link rel='stylesheet' href='build/loading-bar.min.css' type='text/css' media='all' />
<script type='text/javascript' src='build/loading-bar.min.js'></script>
Hope this is help you

Post angularjs form to nodejs Express ( Bad request)

im new in angularJs, im trying to make a basic login with angularJS and nodejs ( server side), i dont care about security for now im just trying to learn how to post. so i made a login form and a controller with angular :
My Login Form :
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="login.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="login.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login()">Login</button>
</div>
</form>
</div>
then my router & controller Angularjs :
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
});
}])
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.login = function() {
$http.post('/api/users/login', $scope.login).success(function (response) {
console.log(response);
// refresh();
});
};
}]);
and Server side i have that :
router.post('/login/', function(req, res) {
// here "/login/" means "/users/login" ( in index of controllers)
console.log(req.body.mail);
var usermail = req.body.mail;
var pass = req.body.password;
console.log(usermail + pass);
User.find({mail: usermail}, function(err, user) {
if (err) {
res.send(err);
console.log("ça marche pas")
} else {
res.json( user );
console.log(user);
}
})
});
server side : it works ( when i use DHC chrome extension to Post) but when im using angularjs view i got that error :
POST http://localhost:3000/api/users/login 400 (Bad Request)
Please help me to solve that, i think i missed something. Thank you in advance.
I think you are sending your login function as in below line:
$http.post('/api/users/login', $scope.login)
You probably want to pass a parameter in your login function that can be sent to server as below:
$scope.login = function(loginData) {
$http.post('/api/users/login', loginData).success(function (response)
Update
You are assigning your form values to $scope.login. If you would create a separate variable for it, for example loginForm, you can send this as valid JSON to your API:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="loginForm.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="loginData.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login(loginData)">Login</button>
</div>
</form>
</div>
And .js:
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loginForm = {
mail: '',
password: ''
};
$scope.login = function(loginData) {
// Check what this prints out:
console.log(loginData);
$http.post('/api/users/login', loginData).success(function (response) {
console.log(response);
// refresh();
});
};
}]);

how to send values from view controls to angularjs controller..?

In my Angularjs MVC application i write code for lo-gin which accept values from two text boxes as user name & password
my Angularjs controller code is as which works fine but problem with view
$scope.Login = function Login(U_Name, U_PWD) {
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name,
User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
this code is executing on ng-click event but doesn't accept values from input boxes
my view code is as:
<div ng-app="angApp">
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
Your problem is that you are not passing U_Name, U_PWD variable to Login function. You need to pass input values to your function.
There are 2 ways of achieving it.
First, Pass the model directly to function like
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
Second, Use $scope.U_Name and $scope.U_PWD
$scope.Login = function() {
var U_Name = $scope.U_Name,
U_PWD = $scope.U_PWD
}
In controller get this
this example without set login parametr
$scope.Login = function Login() {
var U_Name = $scope.U_Name;
var U_PWD = $scope.U_PWD;
console.log($scope.U_Name);
console.log($scope.U_PWD);
}
And you can set login function parrameters that model
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
use this
data:
{
User_Name: $scope.U_Name,
User_PWD: $scope.U_PWD
}

How to trigger ng-repeat in Angularjs with MVC application..?

i'm creating an application in AngularJS with MVC
i write code in AdminCtrl.js is:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
}).success(function data() {
$scope.products = data.result;
})
}
}]);
i'm able to get data as collection from back end now using $scope i'm binding it to my view as:
<div id="divTest" ng-controller="AdminCtrl">
<div ng-repeat="item in products">
Prod_ID:{{item.Prod_ID}}
Prod_Name:{{item.Prod_Name}}
Prod_Price:{{item.Prod_Price}}
Prod_Desc:{{item.Prod_Desc}}
</div>
</div>
on the view i'm not able to bind this data using ng-repeat, but this data is visible on console.
please any one help me to figure out the issue what i'm missing.
Thanks in advance.
i did only a little bit mistake, i was binding ng-app to but in the sense it should be bind with now it's working.
my new code like as .....
<body ng-app="angApp">
<script src="Scripts/app/AdminCtrl.js"></script>
<div id="alert" class="alert"></div>
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
change
.. }).success(function data() {
$scope.products = data.result;
})..
to
.. }).success(function (data) {
$scope.products = data.result;
})..
ie:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
//data needs to be inside bracket
}).success(function (data) {
$scope.products = data.result;
})
}
}]);

Submit form with ng-submit and trigger synchronous post request

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.
However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.
How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?
My form of course looks basically like the following:
<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
...
<input type="submit" value="Submit">
</form>
The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!
TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.
http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview
Please check this plunkr
Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function($event) {
if ($scope.text) {
$scope.list.push(this.text);
if(this.text === 'valid'){
$event.target.submit();
}
$scope.text = '';
}
};
}
Try inside formAction after you've submitted the data:
$route.reload();
I dont think you need to do a full page refresh. You have a single page app I am assuming; use it. Try something like this:
<section class="contact">
<article>
<h1>Contact</h1>
<form role="form" name="contactForm" ng-submit="formSubmit(contactForm)">
<div class="form-group">
<input class="form-control" ng-model="name" name="name" id="name" type="text" placeholder="Name" required/>
</div>
<div class="form-group">
<input class="form-control" ng-model="email" name="email" id="email" type="email" placeholder="Email Address" required/>
</div>
<div class="form-group">
<textarea class="form-control" ng-model="message" name="message" id="message" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
<a class="btn btn-default btn-lg" href='mailto:me#something.net'>Or email me</a>
</div>
</form>
</article>
'use strict';
MyApp.controller('ContactController', function ContactController ($scope, EmailService) {
$scope.formSubmit = function(form) {
EmailService.send(form).then(function(data) {
if(data.message.sent) {
$scope.resetForm();
alert("Message Sent");
}
else {
alert("Something went wrong. Try emailing me.");
}
});
}
$scope.resetForm = function() {
$scope.name = "";
$scope.email = "";
$scope.message = "";
}
});
MyApp.factory('AjaxService', function AjaxService ($q, $http) {
return {
http: function(ajaxParams) {
var deferred = $q.defer();
$http(ajaxParams)
.success(function (data, status, headers, config) {
deferred.resolve({
success: true,
status: status,
message: data
});
})
.error(function (data, status, headers, config) {
deferred.reject({
success: false,
status: status,
message: "Http Error"
});
});
return deferred.promise;
}
}
});
MyApp.factory('EmailService', function EmailService (AjaxService) {
return {
send: function(emailData) {
var ajaxParams = {
method: 'POST',
url: ''//where ever your form handler is,
data: {
name: emailData.name.$modelValue,
email: emailData.email.$modelValue,
message: emailData.message.$modelValue
},
cache: false
}
return AjaxService.http(ajaxParams);
}
}
});

Resources