Refresh/ Re Render the UI once Submit button is clicked - javascript

Currently I am using AnularJS to update the value from JSON file and Once I click Submit button , I want to clear the whole DOM and refresh the UI and update the contents. Can you please help here
Here Value1 and Value2 comes from two different functions but sometimes . Value2 will be null and only Value1 will be present. but still Value2 will be shown with Old value and Value1 with updated value after clicking submit button.
Is there any way in AngularJS to refresh the DOM before updating the values. so that once i click submit i should be seeing only Value1
var app = angular.module('myApp', ['angular-loading-bar']);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'one.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value1 = response.data
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'two.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value2 = response.data
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="Controller">
<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">{{value1}}</span>
<span id="message">{{value2}}</span>
</div>
</div>
</div>
</body>
</html>

There is no need to refresh UI as angular data-binding does the job.
Changing the ng-click="firstFunction();secondFunction();"
to ng-click="value1=null;value2=null;firstFunction();secondFunction();" may help.

Related

Input field should not clear after submit using angularjs

HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!
You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}
Place your Submit Button inside the Form Element then try it it will clear the input after the submission.
your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure

How to bind value with $scope to view with ng-model from controller that define in state ui-router?

I used mechanism for transferring state ui-router. With state "inputcontract" that I have defined, when processed (http://cem.survey.local/#/inputcontract/SGD621262), it will pass parameter "sohd" to function "$scope.getSurveyContent($scope,sohd)" in controller "accountController" , this function will send the request to the server to retrieve data returns in json structures. The problem is that I cannot bind value to view by using $scope with json return "$scope.account =response.data_cusinfo[0]", if bind successfully it will appear dynamic on view HTML. How can i do that? Thank you very much.
Here is app.js
var app = angular.module('outbound', ['ngMaterial', 'ui.router'])
.constant('API_URL', 'http://cem.survey.local/');
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('inputcontract', {
url: "/inputcontract/:sohd",
controller: 'accountController'
})
})
Here is accountController.js
app.controller('accountController', function ($scope, $http,$templateRequest, $sce, $compile, $mdDialog, $mdSidenav, $mdMedia, API_URL, $stateParams) {
if (typeof $stateParams.sohd === 'undefined') {
return;
}
$scope.account = {};
var sohd=$stateParams.sohd;
$scope.getSurveyContent= function($scope,sohd)
{ var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).success(function (response) {
$scope.account =response.data_cusinfo[0];
}).error(function (response) {
});
}
//Send Request to server with sohd
$scope.getSurveyContent($scope,sohd);
Here is the view
<html lang="en-US" ng-app="outbound">
...
<div ng-controller="accountController">
...
<td style="width: 150px">Khách hàng
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.CustomerName" >
</div></td>
<td>CMND
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Passport" >
</div>
</td>
<td>Ngày tháng năm sinh
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Birthday">
</div></td>
...
</div>
...
</html>
Assuming the $http post is successful, you don't need to pass $scope on your getSurveyContent function. Also, success and error are deprecated - you should use then. Try this:
$scope.getSurveyContent = function(sohd) {
var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).then(
function successCallback (response) {
$scope.account = response.data.data_cusinfo[0];
},
function errorCallback (response) {
}
);
}
//Send Request to server with sohd
$scope.getSurveyContent(sohd);

Posting data to MVC Controller using AngularJS

I have a simple html form with 2 textboxes and a button as following:
<div class="container" ng-controller="GetStudentController">
<div class="form-group" style="padding-bottom:40px;">
<h2 style="text-align:center;">Index</h2>
<input id="Text1" class="form-group form-control" ng-model="ime" type="text" />
<input id="Text1" class="form-group form-control" ng-model="prezime" type="text" />
<input type="button" style="float:right;" class="form-group btn btn-primary" ng-click="snimi(ime,prezime)" value="Snimi" />
</div>
</div>
And this is my AngularJS code:
var app = angular.module("myApp", []);
app.service("GetStudentsService", function ($http) {
this.getData = function ()
{
return $http({
metod: "GET",
url: "/Home/GetStudent"
}).success(function (data) {
return data;
}).error(function () {
alert("error");
return null;
});
}
this.PostData = function (data)
{
$http.post("/Home/SnimiStudenta",data)
.success(function () {
getData();
}).error(function (response) {
alert(response);
});
}
});
app.controller("GetStudentController", function ($scope, GetStudentsService) {
$scope.data = null;
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
$scope.snimi = function (ime, prezime) {
var data = $.param({
fName: ime,
lName: prezime
});
GetStudentsService.PostData(data);
};
});
And this is the action responsible for saving the record to the DB:
[HttpPost]
public void SnimiStudenta(// I would like to pass an Student object here)
{
Student s = new Student();
s.Ime = "1";
s.Prezime = "2";
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
I have a few questions:
How can I mark my values from my textboxes and pass them as an Student object into my action
How can I bind the table upon saving the new record into the DB. As you can see I'm calling the function getData(); but it says its undefined...
Can someone help me out with this please?
Thanks!
You have to build a js object which looks similar to your C# class (In terms of the property name) which you use as the parameter for your action method, and post the js object
$scope.snimi = function (ime, prezime) {
var data = { Ime: ime, Prezime: prezime};
GetStudentsService.PostData(data);
};
And your action method,
[HttpPost]
public void SnimiStudenta(Student s)
{
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
As far as why you get an "undefined" error when you call getData(), it is not because getData is undefined, but because getData returns a promise containing just the data, not the whole response. So change:
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
to:
GetStudentsService.getData().then(function (data) {
$scope.data = data;
});

AngularJS: Call httpget on value change from textbox

I have a web service which returns json file on call with a parameter for the id of an entry. I have a angular method that returns the data returned from that method. I have no idea how to recall the service when the input of the id has changed as I want to recall that method when a new value has been supplied.
The parameter that I pass in for the Id is called Reference. The HTML returns object with a reference of 1234 but if I change the value I dont know how to recall the service.
This is what I have so far:
Angular:
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : '1234' }
})
.then(function (response) {
$scope.booking = response.data
});
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
Html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/angular.js"></script>
<script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
{{test}}
{{Reference}}
<br />
<br />
<input type="text" ng-model="Reference" ng-change="booking"/>
{{booking}}
</body>
</html>
Change ng-change="booking" to a function that is called everytime that models Refences changes:
$scope.getReference = function(referenceNumber){
$http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : referenceNumber}
}).function (response) {
$scope.booking = response.data
});
}
<input type="text" ng-model="Reference" ng-change="getReference(Reference)"/>
try this :
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
$scope.refresh = function(){
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : $scope.Reference }
})
.then(function (response) {
$scope.booking = response.data
});
}
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
and html
<input type="text" ng-model="Reference" ng-change="refresh()"/>
ng-change call the given function each time the input change.
refresh() don't need a parameter because it use $scope.Reference

How to submit a straightforward form using Angular

Using angular, I want to submit a form and store the response. My code looks something like this:
<form ng-controller="myController" action="myAction" method="POST">
<input type="text" name="name" />
<input type="submit" ng-click="submit" />
</form>
<script>
function myController($scope, $http) {
$scope.submit = function() {
$http.post(url, data).success(function(data) {
$scope.result = data;
});
}
}
</script>
How do I get url and data to be the form action and inputs, respectively? I don't want to send JSON, I want the server side to see this is a regular HTML form submit.
Thank, #Vincent Ramdhanie, for pointing me in the right direction. Here's what I ultimately did, using plenty of jQuery thrown in:
function myController($scope, $http) {
$('form').submit(function() {
return false;
});
$scope.submit = function() {
form = $('form');
data = form.serialize();
url = form.attr('action')
$http.post(url, data,
{ headers:
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data) {
$scope.result = data;
}
);
}
}
This is how I accomplish this, start by binding the form data to your model, Then use a transform to transform your JSON data into regular post parameters. This solution depends on the jQuery param() function:
<form ng-controller="myController" method="POST">
<input type="text" name="name" ng-model="name"/>
<input type="submit" ng-click="submit" />
</form>
function myController($scope, $http) {
$scope.name = "";
/* Helper function to transform the form post to a regular post rather than JSON */
var transform = function(data) {
return $.param(data);
}
$scope.submit = function() {
$http.post('myAction', $scope.name, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
})
.success(function (data) {
$scope.result = data;
});
}
}

Categories