AngularJS - inputs in a html-table inside a form - angularjs

It works now...
I GET array and stick name in input, then I change name in input and PUT it.
HTML
<form id="edit">
<table>
<tr>
<th>Name: </th>
<td>
<input id="name" form="edit" type="text" ng-model="name" required>
</td>
</tr>
</table>
<button ng-click="edit()">Submit</button>
</form>
AngularJS
$scope.display = function()
{
var connection = $http(
{
method: 'GET',
url: 'http://localhost:8080/students?id=' + $scope.id
})
.then(function(response)
{
$scope.myArray = response.data;
$scope.name = $scope.myArray[0].name;
})

You need to check the status_code on the response not on response.data:
if (response.status == 200)
{
success();
}
else
{
fail();
}

You should check your $scope.name properly update in controller when you hit the button. your request might be fail because of your $scope.name not update in controller properly.

Related

posting form data from one view to anonther view using angularjs

I have designed below pages using angularJs, there I am using routing and custom service
home.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Home</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="homeApp.js"></script>
</head>
<body>
<div ng-app="homeApp">
<div ng-controller="homeCtrl">
<div ng-view></div>
</div>
</div>
</body>
</html>
homeApp.js
var app = angular.module('homeApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider.
when('/dashBoard',{
templateUrl : 'dashBoard.html',
controller : 'homeCtrl'
}).when('/createCase',{
templateUrl : 'createCase.html',
controller : 'flatCtrl'
}).when('/submitCase',{
templateUrl : 'submitCase.html',
controller : 'flatCtrl'
}).otherwise({
redirectTo : '/dashBoard'
});
});
app.factory('homeService',function(){
var bean = {};
function set(data){
alert("service = "+data);
bean = data;
}
function get(){
return bean;
}
return{
set : set,
get : get
}
});
app.controller('homeCtrl',function($scope){
$scope.validateMe = function(isValid){
if(isValid){
alert("validated");
}
}
});
app.controller('flatCtrl', function($scope,$http,$window,homeService) {
$scope.loadLists = function(){
loadReviewTypes();
loadPriorities();
loadCamTypes();
};
loadReviewTypes = function(){
var onSuccess = function (dataRT, status, headers, config) {
$scope.reviewTypes = dataRT;
};
var onError = function (dataRT, status, headers, config) {
alert("failed");
}
$http({
method : 'POST',
url : 'secondHello?strParam=RT'
}).success(onSuccess).error(onError);
};
loadPriorities = function(){
var onSuccess = function (dataP, status, headers, config) {
$scope.priorities = dataP;
};
var onError = function (dataP, status, headers, config) {
alert("failed");
}
$http({
method : 'POST',
url : 'secondHello?strParam=P'
}).success(onSuccess).error(onError);
};
loadCamTypes = function(){
var onSuccess = function (dataC, status, headers, config) {
$scope.camTypes = dataC;
};
var onError = function (dataC, status, headers, config) {
alert("failed");
}
$http({
method : 'POST',
url : 'secondHello?strParam=C'
}).success(onSuccess).error(onError);
};
loadRatingTypes = function(id){
var onSuccess = function (dataP, status, headers, config) {
$scope.ratingTypes = dataP;
};
var onError = function (dataP, status, headers, config) {
alert("failed");
}
$http({
method : 'POST',
url : 'secondHello?strParam=R&id='+id
}).success(onSuccess).error(onError);
};
$scope.checkWord = function(msg){
$scope.ratingYear = msg-1;
};
$scope.chgRatingType = function(type){
if(type != '0'){
loadRatingTypes(type);
}else {
$scope.ratingTypes = [];
}
};
$scope.checkRatingYear = function(val1,val2){
if(val1 > val2){
alert('Rating year cannot be greater than Assessment year');
$scope.ratingYear=$scope.assessmentYear-1;
}
};
$scope.saveForm = function(){
var onSuccess = function (data, status, headers, config) {
alert(data);
$scope.messages = data;
};
var onError = function (data, status, headers, config) {
alert("failed");
}
alert(123);
$http({
method : 'POST',
url : 'secondHello'
}).success(onSuccess).error(onError);
};
$scope.form = {
};
$scope.postForm = function() {
console.log("posting data....");
alert("form.camNum = "+$scope.form.camNum);
formData = $scope.form;
console.log(formData);
/*$http({method : 'POST',
url : 'thirdHello',
data : JSON.stringify($scope.form)
}).success(function(){
alert("success form data");
}).error(function(){
});*/
$http({
method : 'POST',
url : 'thirdHello',
contentType: 'application/json',
data : JSON.stringify($scope.form)
}).success(function(data, status, headers, config){
alert("success form data ="+data);
homeService.set(data);
$scope.bean = homeService.get();
}).error(function(data, status, headers, config){
});
};
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("flat"), ['flatApp']);
});
dashBoard.html
<div>
<form name ="formDm">
<table border="1">
<tr>
<td>
Party Name : <input type="text" ng-model = "formD.partyNm" name = "partyNm" ng-minlength="5" required>
<p ng-show="formDm.partyNm.$error.minlength">Please enter at least 2 char's</p>
</td>
</tr>
</table>
<!--New Case-->
<a type="submit" ng-href="#createCase">
<button ng-click="validateMe(formDm.$valid)" type="submit">New Case</button>
</a>
<p>{{bean}}</p>
</form>
</div>
createCase.html
<div id="flat" ng-controller = "flatCtrl" >
<form method="post" ng-init="loadLists()">
<div>
<table border="1">
<tr>
<td>
CAM No. : <input type="text" ng-model = "form.camNum" name = "camNum">
</td>
<td>
Party Name : <input type="text" ng-model = "form.partyNm" name = "partyNm">
</td>
</tr>
<tr>
<td>
Review Type : <select ng-model = "form.reviewType" name = "reviewType" ng-filter = "">
<option ng-repeat = "x in reviewTypes" value = "{{x.Id}}">
{{x.strName}}
</option>
</select>
</td>
<td>
Priority : <select ng-model = "form.priority" name = "priority">
<option ng-repeat = "x in priorities" value = "{{x.Id}}">
{{x.strName}}
</option>
</select>
</td>
</tr>
<tr>
<td>
CAM Type : <select ng-model = "form.camType" name = "camType" ng-filter = "" ng-change="chgRatingType(form.camType)">
<option ng-repeat = "x in camTypes" value = "{{x.Id}}">
{{x.strName}}
</option>
</select>
</td>
<td>
Rating Type : <select ng-model = "form.ratingType" name = "ratingType" ng-filter = "">
<option ng-repeat = "x in ratingTypes" value = "{{x.Id}}">
{{x.strName}}
</option>
</select>
</td>
</tr>
<tr>
<td>
Rating Year : <input type = "text" ng-model="form.ratingYear" ng-change="checkRatingYear(ratingYear,assessmentYear)">
</td>
<td>
Assessment Year : <input type = "text" ng-model = "form.assessmentYear" ng-keyup="checkWord(assessmentYear)">
</td>
</tr>
</table>
<a type="submit" ng-href="#submitCase">
<button ng-click="postForm()" type="submit">Submit</button>
</a>
</div>
<p>{{bean}}</p>
</form>
Back To DashBoard
</div>
submitCase.html
<div id="flat" ng-controller = "flatCtrl" >
{{homeService.get();}}
Back To DashBoard
</div>
here I am trying to do routing as well as form submission.
after getting root from dashboard page to cratecase page where I am submitting the form details to server and again getting JSON object from server which I want to display submitCase page.
At home.jsp I have bootstrapped angular with homeApp module.
and after getting routed to from dashboard to createcase I am adding one more app flatApp but submitCase page also has same app and controller still I am not able to populate values being set to bean object in homeService at submitCase page. Where I am making mistake? how do I bring submitCase page to current scope i.e. createCase page as I am able to print that bean object on createCase page after form submission Please help

AngularJS FORM POST

I came across a situation where I need to call server method before continue with the FORM POST in angularJS. If the server method returns an error I need to display it and remain in the same method which ultimately does not do the POST request.
How can I achieve this with AngularJS?
See my code sample below
HTML
<form action="http://app.test.com/ProcessTransaction" method="POST">
<table>
<tr>
<td><input type="hidden" name="Amount" value="25.00" /></td>
</tr>
<tr>
<td><input type="hidden" name="Currency" value="NZD" /></td>
</tr>
</table>
<div class="container-fluid align:left">
<button type="submit" class="btn btn-success" ng-disabled="properties.disabled" ng-click="ctrl.action()">{{properties.label}}</button>
</div>
</form>
Angular Controller
this.action = function action() {
var req = {
method: method,
url: <some_url>,
data: angular.copy(data_to_sent),
params: params
};
return $http(req)
.success(function(data, status) {
$scope.properties.dataFromSuccess = data;
})
.error(function(data, status) {
$scope.properties.dataFromError = data;
})
.finally(function() {
});
}
Okay based on the question OP want's to validate the form and then go for submitting the form values.There are two approaches here
1) Do the form validation on client side using <ng-form> / <form> and required in the input fields.
2) We can skip the traditional way of form submit and just call our submit function on submit click and validate the form from server and if it's success then go for saving the form value or else display errors.
Make below changes for approach (2) as it will be closest for you question.
In HTML
<form>
<table>
<tr>
<td><input type="hidden" name="Amount" value="25.00" /></td>
</tr>
<tr>
<td><input type="hidden" name="Currency" value="NZD" /></td>
</tr>
</table>
<div class="container-fluid align:left">
<button type="submit" class="btn btn-success" ng-disabled="properties.disabled" ng-click="ctrl.action()">{{properties.label}}</button>
</div>
</form>
In JS
this.action = function action() {
var req = {
method: method,
url: <some_url>,
data: angular.copy(data_to_sent),
params: params
};
return $http(req)
.success(function(data, status) {
$scope.properties.dataFromSuccess = data;//here data can contain whether the form is valid or invalid...so create a boolean at server if it's valid or not..
if($scope.properties.dataFromSuccess.isSuccess){
$http.post(URL,formData).success(function(data){
$scope.dataSaved = data;
});
}else{
$scope.properties.dataFromError = data; //set the errors in the scope to display
}
})
.error(function(data, status) { //this error means request has been failed to process not the validation error we are checking at server..
//$scope.properties.dataFromError = data;
})
.finally(function() {
});
}

Angular trouble with $http.get

I just started learning Angular and I am having trouble retrieving data based on a http-get request. It works when I simply retrieve all movies, but not when I try to retrieve movies based on a search term (cfr. search.html). I hope someone can tell me where I went wrong, I really can't see it. Thank you in advance.
app.js:
var app;
(function() {
app = angular.module('imdb', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/search', {
controller: 'SearchController',
templateUrl: 'views/search.html'
})
.when('/movies', {
controller: 'MovieController',
templateUrl: 'views/movies.html' //works fine
})
.otherwise({
redirectTo: '/movies'
});
});
})();
SearchController.js
(function (app) {
app.controller('SearchController', ['$http', '$scope', function ($http, $scope) {
$scope.movies = [];
$scope.searchMovie = function(title) {
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
.success(function(data) {
$scope.movies = data;
});
};
}]);
})(app);
search.html
<div>
<form class="form" novalidate name="searchMovies" ng-submit="SearchController.searchMovie(title)" >
<input type="text" ng-model="title" class="form-control" placeholder="enter title">
<button type="submit" class="btn btn-primary btn-block">Search</button>
</form>
<table class="table">
<thead>
<tr>
<th>poster</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
</tr>
</tbody>
</table>
</div>
Replace
SearchController.searchMovie(title)
by
searchMovie(title)
All expressions are always evaluated on the scope. So the first, incorrect one, will try to invoke the method searchMovie of $scope.SearchController, which doesn't exist.
Also note that success() is deprecated for quite some time now. Use then():
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
.then(function(response) {
$scope.movies = response.data;
});
You should also avoid using string concatenation to pass parameters. Those need to be encoded properly. So rather use
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search', {params: {title: title}})
.then(function(response) {
$scope.movies = response.data;
});

angularjs $http.post with parameters get null

I am using angular for login page but return null parameters to controller.
view page:this my code in view page
<div ng-controller="LoginController">
<form novalidate name="f1" ng-submit="Login()">
<div style="color:rgb(142,2,2)">{{Message}}</div>
<table ng-show="!IsLogedIn">
<!-- Here ng-show="!IsLogedIn" means I want to hide table after loged in-->
<tr>
<td>Username : </td>
<td>
<!-- Here ng-class="Submitted?'ng-dirty':''" Means if submitted (clicked submit button) then make this dirty state
for show red border-->
<input type="text" ng-model="Login.Username" name="cUsername" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error" ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required">Username required</span>
<!-- ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required" Means I want to show this span only when
the control cUsername is invalid-->
</td>
</tr>
<tr>
<td>Password : </td>
<td>
<input type="password" ng-model="Login.pass" name="cPassword" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error" ng-show="(f1.cPassword.$dirty || Submitted) && f1.cPassword.$error.required">Password required</span>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
i need to use the returned value from this factory in other factories.
but get null parametrs
mycontroll.js
angular.module('MyApp')
.controller('LoginController', function ($scope, LoginService) {
$scope.IsLogedIn = false;
$scope.Message = '';
$scope.Submitted = false;
$scope.IsFormValid = false;
$scope.LoginData = {
Username: '',
Password: ''
};
//Check is Form Valid or Not // Here f1 is our form Name
$scope.$watch('f1.$valid', function (newVal) {
$scope.IsFormValid = newVal;
});
$scope.Login = function () {
$scope.Submitted = true;
if ($scope.IsFormValid) {
LoginService.GetUser($scope.LoginData).then(function (d) {
if (d.data.Username != null) {
$scope.IsLogedIn = true;
$scope.Message = "Successfully login done. Welcome " + d.data.Name;
}
else {
alert('Invalid Credential!');
}
});
}
};
})
.factory('LoginService', function ($http) {
var fac = {};
fac.GetUser = function (d) {
return $http({
url: '/login/Login',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fac;
});
logincontrol
[HttpPost]
public virtual JsonResult Login(Login d)
{
using (CrudAngularEntities dc = new CrudAngularEntities())
{
var user = dc.Users.Where(a => a.Username.Equals(d.Username) && a.pass.Equals(d.pass)).FirstOrDefault();
return new JsonResult { Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
You are passing $scope.LoginData to the function LoginService.GetUser. The corresponding server model is Login. Hence its signature needs to be same.
$scope.LoginData = {
pass : '',
Username: ''
};
Then you mapped the ng-models to something else (to Login obj). You may need to replace inputs for username and password with
<input type="text" ng-model="LoginData.Username"
<input type="password" ng-model="LoginData.pass"

angular js search bar, returns only data I entered into search bar

I am trying to enter a country into a search bar, use ng-click or ng-submit to return only the data for the country i entered into the search bar. right now when i submit, i get every country returned and then i can filter to get the country i want. I have all my data in mongolab, i use node js to get my data to my angular js service, then i have an angular js controller that sends data to the view i want. I am using anguler ui router. Here is my service:
angular.module('TravelSite').service('countryService', ['$http', '$q', function($http, $q) {
this.getCountry = function() {
var dfd = $q.defer();
$http({
method: 'GET',
url: '/country'
}).then(function(response) {
console.log(response.data);
dfd.resolve(response.data);
}, function(err) {
console.log('Error: ' + err);
});
return dfd.promise;
};
this.addCountry = function(body) {
var dfd = $q.defer();
$http({
method: 'POST',
url: '/country',
data: body
}).then(function(response){
console.log(response.data);
dfd.resolve(response.data);
}, function(error) {
console.log('error: ' + error);
});
return dfd.promise;
};
}]);
here is my controller:
angular.module('TravelSite').controller('CtrlCountry', function($scope, countryService) {
$scope.addCountry = function(country, cb) {
countryService.addCountry(country).then(function(res) {
});
}
$scope.getCountry = function() {
countryService.getCountry().then(function(dataFromService) {
$scope.countries = dataFromService;
});
}
});
here is my view:
<div>
<div>
<input type="text" ng-model="search.name">
<input type="text" placeholder="name" ng-model="country.name"/>
<input type="text" placeholder="population" ng-model="country.population"/>
<input type="text" placeholder="travel warning" ng-model="country.travel_warning"/>
<input type="text" placeholder="visa" ng-model="country.visa"/>
<input type="text" placeholder="vaccinations" ng-model="country.vaccinations"/>
<button ng-click="addCountry(country)">Create Country</button>
</div>
<form ng-submit="getCountry()">
<input type="text" ng-model="country.name">
<input type="submit" value="Search">
</form>
<button ng-click="addCountry(country)">Create Country</button>
<ul>
<li ng-repeat="country in countries | filter:search">{{country.name}}
{{country.population}} {{country.travel_warning}} {{country.visa}} {{country.vaccinations}}</li>
</ul>
</div>
I have only been coding for about a month, if anyone can help me, i will be extremely grateful.
thanks, and sorry in advance about the terrible looking code.
I'm new to Angular too. :)
I have some code that does exactly the same. I get a lot of info and, then, filter out only what I want.
Whant you can do to filter is to just do some changes on your view.
On your search input box, you can just do this:
<input type='text' ng-model='search'>
Then, on your ng-repeat, you may use:
<li ng-repeat="country in countries | filter: {name: search}">
If you want to filter all the fields, you may use this instead:
<li ng-repeat='country in countries | search'>
Hope it help. :)

Resources