I am new in angular.js and I need to make form with 2 fields for numbers and when I click on submit i need to send to server with json for request result of suma. It will look like: 4 in first field , 4 in second field and on submit it will return result 8.
Thanks guys. Here is code:
<div ng-app="app" ng-controller="HttpGetController">
<p>Num1
<input type="number" name="num1" ng-model="num1" required />
</p>
<p>Num2:
<input type="number" name="num2" ng-model="num2" required />
</p>
<button ng-click="SendData()">Saberi</button> <hr />
{{ PostDataResponse }}
</div>
JS
var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = $.param({ num1: $scope.num1, num2: $scope.num2 });
var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } }
$http.post('localhost:3000', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
}
});
Get the input values and that will be automatically bind to scope. In your controller, just add those two operands.
$scope.sum = $scope.op1 + $scope.opt2;
then post the $scope.sum to server using $http.post() or thru $resource service.
$http POST with JSON Data Example
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = { num1: $scope.num1, num2: $scope.num2 };
$http.post('https://httpbin.org/post', data)
.then(function (response) {
$scope.PostDataResponse = response.data.data;
})
}
});
The DEMO on PLNKR
Related
I am new to this field so need help.I have to post data to API but i am unable to do this.Please help me and let me now the process.
API is: http://trendytoday.in/ers/api/DeviceAlarms
And JSOn format in which i have to send data is:
{
"ers": {
"agency_device_id": "1"
}
}
AngularJS provides the $http service, which has a method most. This can be used like:
var app = angular.module("app", []);
app.controller("HttpGetController", function($scope, $http) {
$scope.SendData = function() {
var data = {
"ers": {
"agency_device_id": "1"
}
}
$http.post('http://trendytoday.in/ers/api/DeviceAlarms', data)
.then(function(res) {
console.log(res);
}, function(err) {
console.error(err);
})
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="HttpGetController">
<button ng-click="SendData()">Submit</button>
<hr /> {{ PostDataResponse }}
</div>
This should be called from a controller or a service, and whichever you choose should have the $http service included as a dependency.
.controller('AppCtrl', function($scope, $http) {
$scope.ers = {
'agency_device_id' : ''
};
$scope.submit = function(){
var link = 'http://trendytoday.in/ers/api/DeviceAlarms';
$http.post(link, {ers: $scope.ers},{headers: {'Content-Type': 'application/json'} }).then(function (res){
$scope.mssg = res.data.ers.resMessage;
$scope.resp = res.data.ers.response;
I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
.controller('LoginConnect', ['$scope', 'connecting',
function(connecting, $scope){
$scope.user = {};
var inputLogin = $scope.user.login;
var inputPassword = $scope.user.password;
$scope.connect = function (){
connecting(ConnectingFactory);
};
}
])
.factory('connecting', ['$http','$q', function ($http,$q,inputLogin, inputPassword, ConnectingFactory){
var ConnectingFactory = {};
console.log(ConnectingFactory);
ConnectingFactory.login = function(){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: inputLogin, password: inputPassword}
})
.success(function(result){
deferred.resolve(result);
var promise = deferred.promise;
promise.then(function(result){
console.log(result);
// jsonTab = angular.fromJson(result);
// $scope.result = result["data"];
// $scope.user.token = result["data"];
});
})
};
return ConnectingFactory;
}]);
;
And here the HTML :
<!-- User Connection -->
<form name="userConnect" ng-submit="connect()" novalidate ng-controller="LoginConnect">
<label>
Enter your name:
<input type="text"
name="myEmail"
ng-model="user.login"
/>
</label>
<label>
Enter your Password:
<input type="password"
name="password"
ng-model="user.password"
/>
</label>
<input type="submit" value="Connection">
<p>resultat : {{result}}</p>
<p ng-model="user.token">
token : {{mytoken}}
</p>
<p ng-model="user.datab">
datas : {{datab}}
</p>
<br><br><br>
</form>
Hi, I m new in Angular Js developpement, i have no error but not any data in sent to the API. I think their is no link between my function "connect()" and the factory. Could you help me pls ?
Don't use the success method either way.Both methods have been deprecated.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Here is the shortcut method
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Here is a longer GET method sample
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Official Documentation
Regarding the factory , call it correctly as ConnectingFactory.login().
Also, the order here is incorrect, as pointed out by Harry.
['$scope', 'connecting',
function(connecting, $scope){
I've subscribed in my controller on socket event.
When some event has come, i need to get some data from server (i try to call lb.get() as a function into some factory).
$scope.counter = 0;
$scope.$on('lEvent', function (event, response) { // socket event
$scope.counter ++;
console.log('counter '+$scope.counter);
lb.get(response[0]).then(function(response){
var Item = {
id: response.id,
mime: response.mime,
name: response.name,
};
$scope.items.push(Item);
console.log("$scope.items"+$scope.items.length);
});
});
// here is a function in my factory
get: function(id) {
deferred = $q.defer();
$http({
method: "post",
url: url,
data: $.param({id: id}),
headers: header
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
}
Imagine, i've got 5 socket events, but function lb.get() has called a 4 (or 3) times instead of 5. You can see the result of calling in console:
As you can see, the function lb.get() was called 4 times instead of 5.
I think, i need something like a request queue.
You don't have handle for the error response method get. Maybe in this case, your response is disappear.
You don't need a request queue.
See example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleOneController', function($scope, ServiceExample) {
$scope.counter = 0;
$scope.successCounter = 0;
$scope.errorCounter = 0;
$scope.$on('raise.event', function(event, value) {
console.log('counter', $scope.counter);
$scope.counter++;
ServiceExample.get(value).then(function() {
console.log('success response:', $scope.successCounter);
$scope.successCounter++;
}).catch(function() {
console.log('error response:', $scope.errorCounter);
$scope.errorCounter++;
});
});
})
.controller('ExampleTwoController', function($scope) {
$scope.raiseValue = "www.google.com"
$scope.raise = function(val) {
$scope.$emit('raise.event', val);
};
})
.service('ServiceExample', function($http) {
return {
get: function(url) {
return $http({
method: "GET",
url: url
});
}
}
});
.errors {
color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ExampleApp">
<div ng-controller="ExampleOneController">
<h3>
ExampleOneController
</h3>
<form name="ExampleForm" id="ExampleForm">
<pre>counter : {{counter}}</pre>
<pre>successCounter: {{successCounter}}</pre>
<pre class="errors">errorCounter: {{errorCounter}}</pre>
</form>
<div ng-controller="ExampleTwoController">
<h3>
ExampleTwoController
</h3>
<form name="ExampleForm" id="ExampleForm">
<input ng-model="raiseValue">
<br>
<button ng-click="raise(raiseValue)" simple>
Send request to "{{raiseValue}}"
</button>
</form>
</div>
</div>
</body>
I'm trying to have an item in HTML update after a successful post query, but I can't seem to get it to work. Here's the HTML side:
<div class='container' ng-controller='MainController as inputControl' >
<div class='row well well-sm'>
<div class='col-md-6'>
<h2>Input Parameters</h2>
<form name='addform' ng-submit='inputControl.mainAddition()'>
<label>Number 1:</label>
<input ng-model='inputControl.inputData.num1' type="number" />
<br>
<label>Number 2:</label>
<input ng-model='inputControl.inputData.num2' type="number" />
<br>
<input type='submit' value='Add them!'/>
</form>
</div>
<div class='col-md-6'>
<h2>Result</h2>
<P>{{inputControl.resultData}}</P>
</div>
</div>
</div>
And here's the Angular side:
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
var controller = this;
this.inputData = {};
$scope.resultData = 0;
this.mainAddition = (function() {
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
$scope.resultData= (data);
});
this.inputData = {};
});
}]);
The console log shows the correct response from the server, but the resultData in HTML isn't populating.
Edit:
Yeah, sorry, I totally mixed up $scope and this. Find below working code
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
this.inputData = {};
this.resultData = 0;
this.mainAddition = (function() {
var cntrlCache = this;
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
cntrlCache.resultData= data;
});
this.inputData = {};
});
}]);
The easiest way to correct your snippet is to change $scope to controller in
$scope.resultData= (data);
since you've already declared var controller = this in the beginning.
Since the response is a html,you should use inject $sce service in the controller and do the following in the success method of the $http service
$scope.resultData = $sce.trustAsHtml(data)
Also its really a bad practice to have Async methods in the controller.Try to leverage angular services.
Please refer the SO Answer