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
Related
I'm trying to get the device id getUUID at the time of app login along with username and password. Is the right way to get device id and post it to the server for login.
controller.js
.controller('LoginCtrl', function($scope, $http,$rootScope,$window,$location,$cordovaDevice) {
$scope.login = function () {
var data ={
username : $scope.username,
password : $scope.password
};
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$http.post('login', data, config)
.success(function (data, status, headers, config) {
// $scope.DataResponse = data;
$location.path('#/tab/new-order');
})
.error(function (data, status, header, config) {
$window.alert("username or password incorrect");
});
console.log(device.cordova);
}
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
};
})
html code
<form action="" class="ki-login-form" method="post" accept-charset="utf-8">
<div class="form-group username">
<input type="text" class="form-control" name="username" value="" id="identity" placeholder="Your Name">
</div>
<div class="form-group pin">
<input type="text" class="form-control" name="password" value="" id="identity" placeholder="Your Pin">
</div>
<a type="submit" class="btns" ng-click='login()' >Login</a>
</form>
After login it has to be directed to a page href="#/tab/new-order" in the ionic tab
Add dependency injection $location in controller function like following -
.controller('LoginCtrl', function($scope, $http, $rootScope,$window,$location) {
// Your code
});
Solution for your added comment -
Use following -
Add device plugin : cordova plugin add org.apache.cordova.device
In your controller :
module.controller('MyCtrl', function($scope, $cordovaDevice) {
var uuid = $cordovaDevice.getUUID();
});
Change this
var data = $.param({
username : $scope.username,
password : $scope.password,
});
to
var data = {
username : $scope.username,
password : $scope.password,
};
UPDATE -
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
Hello i need to show the response from a website (200, 404, etc) using REST services.
i have created a partial code but i dont know how show the result
This is js
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http ({
method: 'GET',
url: 'http:/www.google.com'
}).
then(function(response) {
$scope.greeting = response.data;
});
})
and this is html
<body>
<div ng-controller="Hello">
<p>Result = {{greeting.content}}</p>
</div>
</body>
</html>
Thanks for help.
You should really be putting your $http calls into a separate service and injecting that into the controller.
so something like this:
angular.module('demo')
.factory('greetingService', function($http) {
this.getGreeting = function() {
return $http ({
method: 'GET',
url: 'http:/www.google.com'
}).then(function(response) {
return response.data
});
}
};
Then inject the service into your controller and call greetingService.getGreeting and then set your $scope variable to the result.
Also make sure you have the proper headers in your request.
The response is a IHttpPromise<T> which extends IPromise<IHttpPromiseCallbackArg<T>>.
The interface for this looks like this:
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: IHttpHeadersGetter;
config?: IRequestConfig;
statusText?: string;
}
So you can access what you need with:
response.status
With your code:
angular
.module('demo', [])
.controller('Hello', HelloController)
function HelloController($scope, $http) {
$http({
method: 'GET',
url: 'http://enable-cors.org'
})
.then(function(response) {
var text = "The status: " + response.status;
$scope.directResponse = response;
$scope.greeting = {content: text};
$scope.someVariable = text;
});
}
/*
var $http = angular.injector(["ng"]).get("$http");
$http.get("http://enable-cors.org/").then(function(response) {
console.log(response.status);
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="Hello">
<p>Status = {{directResponse.status}}</p>
<p>Result = {{greeting.content}}</p>
<p>Result = {{someVariable}}</p>
</div>
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
.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 can't clarify for myself how to deal with $scope in Angularjs. Although I've resolved my current issue other way, still I need help to get comprehension of $scope usage.
I have the following form (simplified for this example). Index.html:
<form class="form-horizontal" ng-controller="AddItemController as addItemCtrl">
<fieldset>
<legend>New item</legend>
<div class="form-group">
<label for="submittedBy" class="col-lg-2 control-label">Submitted by</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="submittedBy" ng-model="addItemCtrl.item.submitted_by" placeholder="Your name here">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<!--button class="btn btn-default">Cancel</button-->
<button type="submit" class="btn btn-primary" ng-click="addItemCtrl.addItem()">Submit</button>
</div>
</div>
</fieldset>
</form>
app.js:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
var table = angular.element($("#body")).scope();
table.items = data;
});
**this.item={};**
}
}]);
All I want is to get data from the form, send it to the server, get response, update table and then clear the form. The last part is my issue. I am currenly using this.item={} to handle it. But I do want to call it using $scope, so it should be $scope.item={} and then I want to move it inside addItem function. Unfortunately it's not working for either case.
I have this code and it is working as intended, but it seems I just got lucky/unlucky to make it without understanding mechanism.
app.controller('ItemController', ['$scope','$http', function ($scope, $http) {
function getItems(){
$http({
url: "get_items",
method: "GET"
}).
success(function(data, status, headers, config) {
$scope.items = data;
});
}
getItems();
}]);`
UPDATE. This is how my AddItemController looks like at the moment:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
$scope.$$prevSibling.items = data;
$scope.addItemCtrl.item={};
});
}
}]);
It works like I wanted it to. But I don't like $scope.$$prevSibling.items = data; statement, I use it to refresh table which is handled by ItemController, is there a more elegant way to do that?
You don't have to make getItem function, you can just write $http code and it will just work fine, about $scope, just don't use this, it's kind of tricky here, all the variables you want to make just make it with $scope and get it from $scope like this
$scope.item;
$scope.item.getItem = function(){};
var item1 = $scope.item;
And so on.