i tried to make login form with angular js
i have list of user in json file but i can't comapre with the input text from login form
User.json :
[{
"username": "user1",
"password": "pass1"
}, {
"username": "user2",
"password": "pass2"
}, {
"username": "user3",
"password": "pass3"
}, {
"username": "user4",
"password": "pass4"
}]
script.js
var app1 = angular.module('app1', []);
var app2 = angular.module('app2', []);
var app = angular.module('app', ['app1', 'app2']);
app1.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
});
app2.controller('formCtrl', function($scope) {
$scope.login = function() {
if ($scope.username == 'test' && $scope.password == 'test') {
alert('valid username/password ' + $scope.username);
alert('user from json ' + $scope.users);
} else {
alert('invalid username/password ' + $scope.username);
}
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<body ng-app="app">
<div ng-controller="formCtrl">
<form name="form">
First Name:<br>
<input type="text" ng-model="username"><br>
Last Name:<br>
<input type="text" ng-model="password">
<br><br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div ng-controller="jsonCtrl">
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
</body>
</html>
the problem is replace if ($scope.username == 'test' && $scope.password == 'test') with anything compare with json
this my code : Plunker
You were using two different scopes across application. I moved all your markup under the same controller, so that is more simple manage the bindings.
Take a look at this plnkr
var app = angular.module('app', []);
app.controller('formCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
$scope.login = function() {
var u = $scope.users.filter((item) => {
return item.username == $scope.username;
});
if (u[0] && u[0].password == $scope.password) {
alert('correct');
} else {
alert('wr0ng');
}
};
});
<div>
<form name="form">
First Name:
<br>
<input type="text" ng-model="username">
<br> Last Name:
<br>
<input type="text" ng-model="password">
<br>
<br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div>
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
First of all, you should not authenticate user using clear text like that. Your server should do it with hashing table without knowing what is the real password.
Http.get is not synchronous which means that your application will continue its path without waiting for your data. In your plunker your formCtrl doesnt have access to jsonCtrl scope.
You should load your data in a service because it is initialised only once compared to the controller who are initialised everytime you load the page.
Finally you should start by looking at ui.router resolve, it allow you to load your data to your service before the page is displayed which will allow you to compare later.
Related
I am working on school project using angularjs, I don't know why I'm getting this Error: $controller:ctrlreg A controller with this name is not registered.
index.html:
...
<div ng-controller="medscontroller">
<ul>
<li ng-repeat="med in meds | filter:{nom:nom} | orderBy:order">{{med.nom}}</li>
</ul>
</div>
<script >
function medscontroller($scope){
$scope.meds=[
{"nom":"aspirine", "prix":"20"},
{"nom":"doliprane","prix":"15"},
{"nom":"da", "prix":"15"}
];
console.log($scope);
}
</script>
You cannot simply define a controller function like above.
In order for a controller to work, you have to do the following things.
Create an angular app with
var app = angular.module('myApp', []);
Deine a controller for that app with.
app.controller('myCtrl', function($scope) { });
Find a working example here.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
I am trying to use http.get and http.post method in angularJS. My html page and js file are as follows,
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="./../js/app.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
<p>Username : <input type="text" ng-model="name"></p>
<p>Quote : <input type="text" ng-model="quote"></p>
<button ng-click="ctrl.add();" name="button" type="button">Add</button>
<button ng-click="ctrl.retrieve();" name="button" type="button">Retrieve Price</button>
<p>The results here</p>
<table>
<tr>
<th>Quote</th>
<th>Price</th>
</tr>
<tr ng-repeat="q in quotes">
<td>{{q.quote}}</td>
<td>{{q.price}}</td>
</tr>
</table>
</div>
</body>
</html>
and
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 20000;
}])
app.controller('myCtrl', function($http, $scope) {
this.retrieve = function() {
$http.get('http://127.0.0.1:8302/api/stock-service/rest/stock/' + $scope.name)
.then(function (response) {
console.log('inside'+ response);
$scope.quotes = response.data;
}, function (response) {
console.log('came here');
});
}
this.add = function() {
var message = {
userName: $scope.name,
quotes: [$scope.quote]
}
$http.post('http://127.0.0.1:8302/api/db-service/rest/db/add', message)
.then(function(response) {
$scope.quotes = response.data;
}, function(response) {
console.log('error..');
});
}
});
But I couldn't find the output in the browser. Actually, I can see that request is sending through the particular uri. I am sure it is working in the back end at-least http.get method, but I have no idea why I am not getting the output.
In the command line I can see as follows,
2020-08-23 16:42:38.871 INFO 20060 --- [nio-8301-exec-6] y.quotes.query1v7.QuotesRequest : Sending request: https://query1.finance.yahoo.com/v7/finance/quote?symbols=GOOG
Thanks in advance.
Finally I could able to solve this problem by adding cross domain CORS extension in google chrome.
cross domain CORS extension
May be it can be a temporary solution.
This question already has answers here:
Angular $http is sending OPTIONS instead of PUT/POST
(2 answers)
Closed 5 years ago.
I'm new to the AngularJS. I'm using AngularJS 1.3.15 version. When I try to call an api with PUT method, It's generating OPTIONS request. I don't know where I'm doing mistake. I tried so many methods which is suggested in Stockoverflow, but still I'm not getting anything. Please help me to resolve this issue. below are my Controller, Models, html files and Chrome developer tool network activity screenshot.
Controller file users.js
'use strict';
mmlApp_users.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/users/update/:userId', {
templateUrl: 'views/users/update.html',
controller: 'update',
resolve: {
user: function(users, $route){
var userId = $route.current.params.userId
return users.getUser(userId);
}
}
})
.otherwise({
redirectTo: '/users/index'
});
}]);
Model file - users.js
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route', function($http, $location, $route){
var obj = {};
obj.getUser = function(userId){
return $http.get(serviceBase + 'users/view/'+userId);
};
obj.updateUser = function(user){
var config = {
headers: {
'Content-Type': 'application/json'
}
};
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
$http.put(serviceBase + 'users/update/'+user.id+'?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13', userParams, config)
.then(successHandler).catch(errorHandler);
function successHandler(){
$location.path('/users/index');
}
function errorHandler(){
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
Views - update.html
<div>
<h1>{{title}}</h1>
<p>{{ message}}</p>
<form role="form" name="myForm">
<div class="row">
<div class= "form-group col-md-6" ng-class="{error: myForm.first_name.$invalid}">
<label> First Name: </label>
<div>
<input name="first_name" ng-model="user.first_name" type= "text" class= "form-control" placeholder="First Name" required/>
<span ng-show="myForm.first_name.$dirty && myForm.first_name.$invalid" class="help-inline">First Name Required</span>
</div>
</div>
<div class= "form-group col-md-6" ng-class="{error: myForm.last_name.$invalid}">
<label> Last Name: </label>
<div>
<input name="last_name" ng-model="user.last_name" type= "text" class= "form-control" placeholder="Last Name" required/>
<span ng-show="myForm.last_name.$dirty && myForm.last_name.$invalid" class="help-inline">Last Name Required</span>
</div>
</div>
</div>
....
....
....
Cancel
<button ng-click="updateUser(user);" ng-disabled="myForm.$invalid" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
In chrome developer tool network activity screenshot -
try in your factory:
(function () {
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route','$httpParamSerializer',
function ($http, $location, $route, $httpParamSerializer) {
var obj = {};
obj.getUser = function (userId) {
return $http.get(serviceBase + 'users/view/' + userId);
};
obj.updateUser = function (user) {
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
var req = {
method: 'PUT',
url: serviceBase + 'users/update/' + user.id + '?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: $httpParamSerializer(userParams)
};
$http(req)
.then(successHandler)
.catch(errorHandler);
function successHandler() {
$location.path('/users/index');
}
function errorHandler() {
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
})();
And Goog Lock :)
Here is my RestController Class
#RestController
#RequestMapping(value="/user")
public class Test {
#RequestMapping(value="/{userEmailId}",method=RequestMethod.GET)
public ModelAndView getUser(#PathVariable("userEmailId") String userEmailId){
//something goes here and get User class object
ModelAndView mav=new ModelAndView("showuser");
mav.addObject("user", user);//user is User class object
return mav;
}
}
I want to display this user object in showuser.jsp using Angular JS How can I do that?
Below is sample example assuming your user object have firstname and lastname:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<div ng-app="myApp" ng-controller="userController">
<form action="demo_form.html">
First name: <input type="text" name="fname" ng-model="fname"><br>
Last name: <input type="text" name="lname" ng-model="lname"><br>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('userController', function($scope, $http) {
$http({
method : "GET",
url : "/user/xyz#a.com"
}).then(function mySucces(response) {
$scope.fname = response.fname;
$scope.lname = response.lname;
}, function myError(response) {
//handling error
});
});
</script>
Okey, please be patience. I only know jquery and I heard that use AngularJS is something that I should try.
So, what I need to to is visit a page on my local host "../asp/fases/fases-controler.asp"
parse the json that this page shows me ( that is something like this: { "fasekind": [ "AAA", "BBB", "CCC" ] } ) and then mount on client side a list like this:
<ul>
<li><input type="checkbox" /> <label>AAA</label></li>
<li><input type="checkbox" /> <label>BBB</label></li>
<li><input type="checkbox" /> <label>CCC</label></li>
</ul>
I do need a help with this. I only know the jQuery way. I have seen so many tutorials but I don't get it. I receive always Uncaught ReferenceError: $http is not defined and other erros messages.
I don't want someone to do that for me, I just need to figure out how it works.
js controller that I try... it does not work at all.
var app = angular.module("app", []);
app.controller("AppCtrl", function ($http) {
var app = this;
$http.get("../asp/fases/fases-controler.asp")
.success(function (data) {
app.fases = data;
})
})
CONTROLLER
var app = angular.module("app", []);
app.controller("AppCtrl", function ($scope, $http) {
$http.get("../asp/fases/fases-controler.asp")
.success(function (data) {
$scope.fases = data;
});
});
HTML
<div class="grid-12-12" ng-app='currentApp' ng-controller='ACtrl'>
<label>Fases <em class="formee-req">*</em>
</label>
<ul class="formee-list">
<li ng-repeat="list in fases">
<input name="checkbox-01" type="checkbox" />
<label>{{list}}</label>
</li>
</ul>
</div>
JSFIDDLE
I found an answer here, it was missing the JSON parse I guess. This is what I did:
JSON
{
"fasekind": [
"AAA",
"BBB",
"CCC"
]
}
CONTROLLER
function FetchCtrl($scope, $http) {
$scope.url = 'fases/fases-controler.asp';
$http.get($scope.url).success(function (data, status) {
$scope.fasekind = data.fasekind;
}).error(function (data, status) {
$scope.response = 'Request failed';
});
}
HTML
<div class="grid-12-12" ng-controller='FetchCtrl'>
<label>Fases <em class="formee-req">*</em>
</label>
<ul class="formee-list">
<li ng-repeat="foo in fasekind">
<input name="checkbox-01" type="checkbox" />
<label>{{foo}}</label>
</li>
</ul>
</div>