AngularJS - Form Submission - javascript

I've recently started using AngularJS, and even though I am able to send data through $http when the webpage loads, I'm unable to do it when a button is pressed. My code:
<div ng-app="myApp" ng-controller="myCtrl">
Username: <input type="text" id="u" ng-model="username"><br>
Password: <input type="text" id="p" ng-model="password"><br>
Email: <input type="text" id="e" ng-model="email"><br>
First Name: <input type="text" id="fn" ng-model="firstName"><br>
Last Name: <input type="text" id="ln" ng-model="lastName"><br>
<br>
<button onclick="sendData()">Click me</button>
<br>
{{status}}
</div>
<script>
var app = angular.module('myApp', []);
var arr = new Array();
function sendData() {
arr[0] = document.getElementById("u").value;
arr[1] = document.getElementById("p").value;
arr[2] = document.getElementById("e").value;
arr[3] = document.getElementById("fn").value;
arr[4] = document.getElementById("ln").value;
app.controller('myCtrl', function($scope, $http) {
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
});
}
</script>
With that code, the function in app.controller doesn't execute, but if I put it outside of the sendData() function, it does execute, but right after loading the page.
Can anyone help me getting it to work when the button is pressed?

SInce you want to use angular and you use ng-model in your view you should use ng-click on your button:
<button ng-click="sendData()">Click me</button>
Even better you can use ng-submit on your form and use a submit button.
In your controller you will have something like this:
$scope.username = '';
$scope.email = '';
// better have an user object here so you will not have n variables ...
$scope.sendData = function() {
var arr = [];
arr[0] = $scope.username;
arr[1] = $scope.email;
//........
$http.post("../signup.php", {data : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}

You need to define the function on the scope of your controller
HTML
<button ng-click="sendData()">Click me</button>
JS
app.controller('myCtrl', function($scope, $http) {
$scope.sendData = function(
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}
});

Related

Form does not update on view and server in AngularJS?

I have this bug in my web app. So, I have a form where when I edit the form it does not update on view and server. What I want to solve is when I edit my form, I want to update the view and the server. So, here is my code below. Please, check out my code if somethings wrong. Thanks in advance. Any Help?
here is my code.
var app = angular.module("MyApp", ['ngRoute', 'ui.bootstrap']);
app.controller('MyCtrl', function($scope, $window, people) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
$scope.inactive = true;
$scope.updateUser = function(person) {
people.updateUser(person);
};
$scope.confirmedAction = function(person) {
var index = $scope.userInfo.lawyers.map(function(e) {
return e.id;
}).indexOf(person.id);
people.confirmUser(person.id).then(function(data){ });
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
};
});
});
about
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="updateUser(person)">Save</button>
<a class="delete" ng-click="confirmedAction(person);" confirm-click>Confirm</a>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}}</span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
</fieldset>
</form>
</div>
</div>
</div>
services to my backend
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.com/admin/v1/lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.com/admin/v1/lawyers/'+lawyerId+'/confirm');
};
service.updateUser = function (person) {
return $http.put('https://api-dev.mysite.com/admin/v1/lawyers/'+ person.id, person);
};
return service;
});
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
There are a couple of problems here.
Data from the server is not bound to the controller which means it will not display in your view.
The inputs to your form are binding to aliases and not any members of an actual scope
After you submit changes to your data, you need to get updates from your server
The inactive scope value is not updated after you save your data
which means your 'Save' button won't hide after a form is submitted.
First step is populating your $scope.userInfo in your MyCtrl controller. When you set $scope.userInfo in your HomeController only HomeController has access to $scope.userInfo and not MyCtrl.
You need to change your code such that MyCtrl sets $scope.userInfo in it's own scope so that it has access to the data like so:
app.controller('MyCtrl', function($scope, $window, people) {
// This function will now be called so that it can get the userInfo
// from the server and populate into the scope and give the controller
// access.
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
// ...
});
Now you need to actually bind the input of your form to the data in your scope.
<form>
<fieldset ng-disabled="inactive">
<legend>Info</legend>
<b>First Name:</b>
<input type="text" ng-model="userInfo.lawyers[$index].firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="userInfo.lawyers[$index].lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="userInfo.lawyers[$index].email">
<br>
<b>Website:</b>
<input type="text" ng-model="userInfo.lawyers[$index].website">
<br>
</fieldset>
</form>
It's important to remember that Angular needs to bind to data in $scope before it will render changes in the DOM and using person from the person in userInfo.lawyers ng-repeat directive references an alias to a person and not to the actual data in the userInfo scope.
After you submit your changes you're going to want to update your list with new data from the server so include:
app.controller('MyCtrl', function($scope, $window, people) {
// ...
$scope.updateUser = function(person) {
people.updateUser(person)
// Now get the new data.
.then(function() {
return people.getUserInfo();
}).then(function (response) {
// Apply the new data to the scope.
$scope.userInfo = response.data;
});
};
// ...
});
Finally for the Save button issues you need to be sure that isactive value of the scope is set appropriately for when you do and don't want it to appear in the DOM. Setting the value to true hides it while setting to false reveals it. The edit button already toggles this value for you but you can also toggle this value when the function you want it to execute completes. You can do this in the updateUser function:
app.controller('MyCtrl', function($scope, $window, people) {
// ...
$scope.updateUser = function(person) {
// Hide the save button
$scope.inactive = true;
people.updateUser(person)
.then(function() {
return people.getUserInfo();
}).then(function (response) {
$scope.userInfo = response.data;
});
};
// ...
});
Additional resources for AngularJS scopes can be found here.

angularjs- not able to submit data set in textboxes using jquery

I have a form which makes uses of google map's Places API.
My form has following fields:
1) text box to enter name.
2) text box to fetch google address.
3) text box which saves latitude from google address.
4) text box which saves longitude from google address.
And I'm trying to pass all these values to a backend service but the values set by places api is not getting passed as a parameter to the service:
Here's my HTML:
<div ng-app="myApp" ng-controller="myMap">
<form name="addForm" ng-submit="vm.addForm()" novalidate>
<div class="form-group">
<input type="text" name="name" id="name" ng-model="vm.name" placeholder="Name" />
<h2>Address</h2>
<input type="text" id="source_point" name="source_point" ng-model="vm.source_point" placeholder="Enter address here">
<input type="text" id="src_lat" name="src_lat" ng-model="vm.src_lat" placeholder="latitude">
<input type="text" id="src_long" name="src_long" ng-model="vm.src_long" placeholder="longitude">
</div>
<button type="submit">Add Data</button>
</form>
</div>
<div id="source_map"></div>
and my Controller looks like this:
angular.module('myApp', [])
.factory('myService', function($http) {})
.controller('myMap', function(myService, $http, $scope) {
var vm = this;
var map;
var marker;
var latLngC;
var places1 = new google.maps.places.Autocomplete(document.getElementById('source_point'));
google.maps.event.addListener(places1, 'place_changed', function() {
var place1 = places1.getPlace();
var src_addr = place1.formatted_address;
var src_lat = place1.geometry.location.lat();
var src_long = place1.geometry.location.lng();
var mesg1 = "Address: " + src_addr;
mesg1 += "\nLatitude: " + src_lat;
mesg1 += "\nLongitude: " + src_long;
document.getElementById('src_lat').value = src_lat;
document.getElementById('src_long').value = src_long;
});
$scope.post = {};
$scope.post.addForm = [];
$scope.vm = {};
$scope.index = '';
var baseUrl = 'api/';
// function to submit the form after all validation has occurred
vm.addForm = function() {
var dataPost = {
eventName: $scope.vm.name,
eventLocation: $scope.vm.source_point,
eventLocLat: $scope.vm.src_lat,
eventLocLong: $scope.vm.src_long
};
return $http({
method: 'post',
url: baseUrl + 'addFormData',
data: dataPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
});
HERE's a FIDDLE
What could be the possible reason?
Setter to input for longitude and latitude is wrong:
$scope.$apply(function() {
$scope.vm.src_lat = src_lat;
$scope.vm.src_long = src_long;
});
instead of
document.getElementById('src_lat').value = src_lat;
document.getElementById('src_long').value = src_long;
Put values into scope and angular will makes the rest :)

How to use AngularJS $rootScope?

I am passing three $rootScope from process controller to Rating controller so based on the $rootScope status i am enabling and disabling buttons. Edit and view is working good but on $rootScope === 'NewPrt', Once user answered all question i want to enable submit button on 'NewPrt'.
So far i tried below code..
HTML
<button type="submit" class="btn btn-default" ng-disabled="disabledDraft" ng-click="savePRTDraft()" ng-show="showSaveDraftBtn">Save
as Draft</button>
<button type="submit" class="btn btn-primary"
ng-disabled="disableSubmitButton" ng-click="submitClicked()">Submit</button>
ProcessCtrl.js
$scope.gotoQstnPage = function(isNew) {
var qrtUrl = "/createRtgQstnAir/"+$scope.processDTO.processKey + "/"+isNew;
$rootScope.status = 'NewPrt';
$location.path(qrtUrl);
}
$scope.editProcessRating = function(prcsSessionKey) {
var prtUrl = "/getProcessRating/"+prcsSessionKey;
$rootScope.status = 'edit';
$location.path(prtUrl);
}
$scope.viewProcessRating = function(prcsSessionKey) {
var prtUrl = "/getProcessRating/"+prcsSessionKey;
$rootScope.status = 'view';
$location.path(prtUrl);
}
RatingCtrl.js
if(j > $scope.questionnaire.length){
if($rootScope.status ==='edit') {
$scope.disableSubmitButton = false;
$scope.disabledDraft = false;
$scope.showBusDecDropDown = true;
}
$scope.disabledDraft = function(){
if($rootScope.status === 'view') {
return true;
}
else {
return false;
}
}
if ($rootScope.status === "NewPrt" ) {
$scope.disabledDraft = false;
}
You can try like this instead of using $rootScope
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="Controller">
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
</div>
When both conditions are true, enable the submit button:
if ($rootScope ==='edit' || $rootScope ==='NewPrt') {
$scope.disableSubmitButton = false;
}
if you want to use $rootScope you need to inject $rootScope in every controller where you want to use config run any where
like this
var app = angular.module('app');
app.config(function($rootScope){
$rootScope.name = "Hello World"
});
app.controller('home',function($scope,$rootScope){
$scope.name = $rootScope.name;
alert($scope.name)
})

Ionic angularjs change returned null of $scope value?

My html
<input ng-model="query" ng-change="change(text)" type="text" placeholder="Search">
My js
$scope.query = null;
$scope.change = function() {
console.log($scope.query); // null?
$timeout(function() {
$http.get('example.com/' + $scope.query
).then(function(result){
$scope.tracks = result.data.items;
});
}, 1000);
}
Why is my $scope.query always got null within the change function?

using $watch in angularjs

I have a form with 2 input fields and requirement is that once user enters valid data into these
fields, I need to pass the input data to the factory function and get the data from server.To achieve this I thought of using $watch function but stuck at how to know if form is valid in $wathc function and then call the factory function to get data from the server.Here is the code.
Any help would be highly appreciated.
//html
<html>
<body ng-app="myModule">
<div ng-controller="myCtrl">
Product Id: <input type="text" ng-model="myModel.id" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" /><br/>
</div>
</body>
</html>
//js
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', function($scope){
$scope.myModel = {};
var getdata = function(newVal, oldVal) {
};
$scope.$watch('myModel.id', getdata)
$scope.$watch('myModel.productname', getdata)
}]);
Wouldn't you just watch myModel, since the same function is called in both cases?
You could do this with ng-change just as easily.
<html>
<body ng-app="myModule">
<form name="productForm" ng-controller="myCtrl">
<div>
Product Id: <input type="text" name="idModel" ng-model="myModel.id" ng-change="validateID()" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" ng-change="validateProduct()" /><br/>
</div>
</form>
</body>
And your JS would look like this:
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', 'myFactory',
function($scope, myFactory){
$scope.myModel = {};
$scope.validateID = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
$scope.validateProduct = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
}
]);
Using ng-change saves you from having to add a $watch to your scope (they are expensive) and will fire when the user leaves the input box. If you need to catch each keystroke, I would recommend that you use UI-Keypress and run the same functions.
To know if form is valid you have to add a form tag and inside your controller check $valid, on your example the form is always valid becaus you do not have any required field.
See the below example on codepen
The HTML
<div ng-app="myModule">
<div ng-controller="myCtrl">
<form name="myform" novalidate>
Product Id:
<input type="text" ng-model="myModel.id" />
<br/>
Product Name:
<input type="text" ng-model="myModel.productname" />
<br/>
</form>
<br/>
<div>{{result}}</div>
<div>Form is valid: {{myform.$valid}}</div>
</div>
</div>
The JS
var myModule = angular.module('myModule', []);
myModule.controller('myCtrl', ['$scope', function ($scope) {
$scope.myModel = {};
$scope.result = "(null)";
var getdata = function (newVal, oldVal) {
var valid = null;
if ($scope.myform.$valid) {
valid = "is valid";
} else {
valid = "is INVALID";
}
$scope.result = "Changed value " + newVal + " form " + valid;
};
$scope.$watch('myModel.id', getdata);
$scope.$watch('myModel.productname', getdata);
}]);

Categories