I've just started getting into using Angular and having an issue displaying a single record that is being returned from using $http (get). I'm getting the data back correctly. This is the html I've got....
<div ng-controller="UserDataController as udCtrl">
Name: {{udCtrl.user.name}}
</div>
<div id="debug" style="margin-top:24px;border:solid 1px #900;background:#efefef;min-height:100px"></div>
have also tried and a couple of other variations...
Name: {{udCtrl.name}}
Javascript:
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var user=this;
user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
This is what is returned in JSON format and I can see this in the little debug area I created.
{"data":{"id":"1","name":"Joe Bloggs"}
if I change the html to use the code below it works.
<div ng-controller="UserTest as udCtrl">
Name: {{udCtrl.user.name}}
</div>
I just cannot see where I'm going wrong and why it will not display the returned name.
Define the user variable on $scope and access it with $scope.user. You are having referance problem.
Example
//Define user variable like this.
$scope.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
$scope.user=response.data;
}
}
EDIT
If you want to use udCtrl referance define variable under thisvariable on controller.
//Define user variable like this.
var ctrl = this;
ctrl.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
ctrl.user=response.data;
}
}
EDIT 2 FOR ABSOLUTE ANSWER
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var udCtrl=this;
udCtrl.user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
udCtrl.user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
Related
I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})
Very new to Angular.js and having an issue that I cannot figure out. This is my html
<user-details></user-details>
This is my angular code:
angular.
module('rtcTimesheet').
component('userDetails', {
template:
'<p>Hi {{$ctrl.username}}</p>',
controller: function UserDetailsController(globalDataService,$http) {
if(globalDataService.getServicePath()) {
try {
this.username="name here";
this.userId=""
$http({
method: 'GET',
url: globalDataService.getServicePath()+'login.php',
params: {
t: "log",
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("<p>ERROR: " + response.data.ErrorMessage+"</p>");
} else {
username=response.data.name;
userId=response.data.id;
$("#debug").append(this.username);
}
},function (err){
$("#debug").append("ERROR http: "+err.status);
});
} catch(err) {
$("#debug").append("CATCH ERROR: "+err.status+"<br/>");
}
} else {
$("#debug").append("<p>Unable to get service path...</p>");
}
}
});
I know the data is being returned correctly, as I can output it using the
$("#debug").append(this.username)
When the page is loaded it just displays the initial 'name here'. Probably has something to do with the slight delay of getting the data back from the database, but no idea how to get around this?
Your variable referance is incorrect. Check the code bellow to use controllerAs refferance with _self.
angular.
module('rtcTimesheet').
component('userDetails', {
template:
'<p>Hi {{$ctrl.username}}</p>',
controller: function UserDetailsController(globalDataService,$http) {
if(globalDataService.getServicePath()) {
try {
var _self = this;
_self.username="name here";
_self.userId=""
$http({
method: 'GET',
url: globalDataService.getServicePath()+'login.php',
params: {
t: "log",
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("<p>ERROR: " + response.data.ErrorMessage+"</p>");
} else {
_self.username=response.data.name;
_self.userId=response.data.id;
$("#debug").append(_self.username);
}
},function (err){
$("#debug").append("ERROR http: "+err.status);
});
} catch(err) {
$("#debug").append("CATCH ERROR: "+err.status+"<br/>");
}
} else {
$("#debug").append("<p>Unable to get service path...</p>");
}
}
});
I have created a service and I using that for my login:
EDIT: Added the 'success' and 'error' code.
EDIT 2: I am developing an iOS mobile application which includes Javascript/AngularJS. So is there a way to view errors as alerts..
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert("here:1");
return jsonObj;
} else {
alert("here:2");
// invalid response
return $q.reject(jsonObj);
}
}).error(function(response) {
//do error
//comes here when no internet connection is found..
alert("here:3");
return $q.reject(response.data);
});
}
}
})
I have also included this in app.js:
var app = angular.module("myApp", ['starter.services'],function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
My actual url looks like this:
'http://' + ipAdd + ':8080/loginuser/user.cgi?ACTION=login&LOGIN=' + name + '&PASSWORD=' + pw;
I have tried this approach too: https://stackoverflow.com/a/25570077/5876598
My service is not returning anything..
I want to know if I'm doing mistake in my url formation, or while sending data.
Thanks.
The best way to know where the mistake comes from is to check the 'network' tab on your navigator developer console.
Assuming you are runing on linux or mac, you can also try to use CURL to have an idea of what return the url you are trying to reach.
We can't help you with the code only.
I added a deferred promise in my service.
I also changed "success().error()" to ".then(function(data, status, headers, config){}) . Don't know why it didn't work when I used success and error.
Actually previously I noticed some issue while rendering promise itself in service. Follow the below structure
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
})
.controller('SomeCtrlName',function(Login){
//pass your parameter to below service.
Login.loginUser().then(function success(){
//write success code here
},function error(){
//write error code here
)};
})
I'm trying to call a function in my jointController from other javascript file.
var app1 = angular.module('jointApp',[]);
var createStateBox = function(label,color){
var state = new uml.State({
position: {x: 0, y: 0},
size: {width: 200, height: 100},
name: "<<"+label+">>",
events: [label+" box"],
attrs:{rect:{fill:color},path:{"stroke-width":0}}
});
app1.controller('jointController', function($scope) {
$scope.setDecision(state);
alert("This is reached");
});
paper.model.addCell(state);
}
Here is the code in jointMod.js which contains jointController
var app = angular.module('jointApp', []);
function JointController($scope, $http, $filter) {
$scope.list = [];
$scope.newMsg = 'hello';
$scope.newDecision;
$scope.setMsg = function(msg) {
$scope.newMsg = msg;
}
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
msg: $scope.newMsg
})
});
$scope.setDecision = function(decision){
$scope.newDecision = decision;
alert("one two one two")
console.log(decision);
}
$http({
method: 'POST',
url: 'http://213.65.171.121:3000/decision',
data: $scope.newMsg,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent("action") + "=" + encodeURIComponent(obj));
return str.join("&");
}
}).success(function(data, status, header, config) {
$scope.list.push(status);
}).error(function(data, status, header, config) {
$scope.list.push(status);
});
};
};
I have the alert and console log in there to make sure if they can be reach but they do not responed.
The code you provided will not function as you may think. Atleast not if you use both together.
Both codes introduce a new module jointApp and actually only the first one defines a controller. The $scope of that controller is NOT the same of the function in your second code.
If you want to call a method from outside of a controller take a look at events in angular. That would be the best way to archive this. You could also use a dummy object and two-way-bind it (scope: { dummy: '=' }) and then call the method you create on that object in your directive from other code-parts.
Take a look at this plnkr demonstrating both approaches.
http://plnkr.co/edit/YdcB10UpXGqKAxYzXISL?p=preview
I'm trying to come to grips with created an angularjs Contact form. Below is a link of what I have created thus far. Click Here I fill I am on the write track with the code i have written
var app = angular.module("myApp", []);
app.controller("contactCtrl", function ($scope) {
$scope.success = false;
$scope.error = false;
$scope.send = function () {
var htmlBody ='<div>Name: ' + $scope.user.name + '</div>' +
'<div>Email: ' + $scope.user.email + '</div>' +
'<div>Message: ' + $scope.user.body + '</div>' +
'<div>Date: ' + (new Date()).toString() + '</div>';
$http({
url: 'https://api.postmarkapp.com/email',
method: 'POST',
data: {
'From': 'foo#foo.com',
'To': 'me#gmail.com',
'HtmlBody': htmlBody,
'Subject': 'New Contact Form Submission'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '8569dcd45-6a1a-4e7b-ae75-ea37629de4'
}
}).
success(function (data) {
$scope.success = true;
$scope.user = {};
}).
error(function (data) {
$scope.error = true;
});
}
});
However I am receiving two errors
And also
{"error": "Please use POST request"}
Does anyone know how I can solve this issues, I've wasted too many hours trying to get my head around it?
You don't declare the $http. It should be:
app.controller("contactCtrl", ['$scope','$http',function ($scope,$http){
// your code
}]);