I'm new to angular and buildig an application that reads data from a API and renders it in an HTML table. For the moment I m trying to see how I can manipulate the table data and thereby changing the model (JSON). I understand this would need API support to make those changes, but for the moment I'd like to try this with mock data inside the Javascript.
Can you please look into this Fiddle code and tell me how I can do that ?
(function() {
var app = angular.module('myApp', []);
app.controller('PeopleController', function($scope, $http) {
$http({
url: "https://api.myjson.com/bins/584d5",
method: "GET"
}).success(function(data,status) {
$scope.people = data.people;
});
});
})();
Thanks
Code Pen Link
So you'd like to change the JSON? you can try a PUT.
Here's your codepen modified: http://codepen.io/anon/pen/qZRYxZ?editors=1010
$scope.myData = {"people":[{"personName":"Scott Walker","personAge":"43","dateOfBirth":"09-12-1972","location":"Leeds","gender":"male"},{"personName":"Paula Lamb","personAge":"38","dateOfBirth":"02-01-1978","location":"Alberta","gender":"female"},{"personName":"Jonathan Joestar","personAge":"22","dateOfBirth":"02-28-1850","location":"UK","gender":"male"}]};
$http.put('https://api.myjson.com/bins/584d5', $scope.myData)
.success(function (data) {
// alert("success!");
});
Created a plunker for you. Basically you can just call the http request to the place where the json file is located. So in this case it is just root, but if it is in a map, just follow the path relative from index.
$http({
url: "example.json",
method: "GET"
}).success(function(data, status) {
console.log($scope.people);
$scope.people = data.people;
});
https://plnkr.co/edit/LmoRco8FN4Ck8xZ7bM2x
Related
Trying to make ajax request when searched data is not found in object.
Html:-
Search programming languages: <input type="Text" ng-model="out.pl">
<div ng-controller="MyContRollEr">
<table border="2">
<tr>
<td>Programming Language:</td>
<td>Percentage:</td>
<td>Salary:</td>
<td>People:</td>
<td>Started Date:</td>
</tr>
<tr ng-repeat="data in info | filter:out">
<td>{{data.pl}}</td>
<td>{{data.percent}}</td>
<td>{{data.salary |currency:'Rs.'}}</td>
<td>{{data.people | number :2}}</td>
<td>{{data.date | date:"yyyy/MM/dd"}}</td>
</tr>
</table>
Controller:-
var app = angular.module('app',[]);
app.controller('MyContRollEr',function($scope) {
var info = [
{pl:'php',percent:'10%',salary:10000000,people:234524},
{pl:'Java',percent:'20%',salary:9822200,people:234443},
{pl:'python',percent:'10%',salary:8739300000,people:2345521)},
];
$scope.info = info;
});
My Function :-
function sendRequest(){
$http({
method:'POST',
url:'index.php',
data:{search:'data'}
}).then(function(data) {
$scope.out = data;
})
}
How to do this combining my controller, function and model.
,This is where angular service comes into play. You should make a new file for both controllers and services. For the sake of simplicity though, you can just add the following code into your current file AFTER the controller.
app.service('myService',function($http) {
this.sendRequest = function() {
$http({
method:'POST',
url:'index.php',
data:{search:'data'}
}).then(function (response) {
console.log(response);
return response.data; // Most APIs have the "data" in the response object. But you can take this out if the console log doesn't show that key in the object.
})
}
)
Once that is done, you'll inject your service into your controller here:
app.controller('MyContRollEr',function($scope, myService) { // Notice that the service is a parameter in controller now.
Next, lets call do the POST by hitting the service. Inside of your controller block, write the following:
myService.sendRequest().then(function (response) {
console.log(response);
})
If you aren't using Gulp (or something similar), then you will need to add the service into your index.html(Or whatever file is your base html file) file just like you did(I assume) with your controller.
Let me know if you have any questions!
i'm trying to move to my account.html from my login.html, using javascript, where i in login.html there will be a validation from MongoDB. And if it's the same data, it was supposed to go to acoount.html, but it doesn't. This is my javascript:
.controller('LoginCtrl', function($scope, $state, $ionicPopup, AuthService) {
$scope.data = {};
$scope.login = function(data) {
var formdata = {
num : $("#num").val(),
pw : $("#pw").val()
};
var Jformdata = JSON.stringify(formdata);
//var url = $location.url();
console.log(Jformdata);
$.ajax({
url : "/ProjectSinarmas/submit",
context : document.body,
type : 'POST',
data : Jformdata,
contentType : "application/json"
}).done(function (response){
//console.log(response);
if(response == "true"){
//$state.go('main.account');
var path = $location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
alert("Login Success");
}else{
$scope.showAlert('Nomer Telephone dan PIN Salah');
}
});
};
I got this error response from my html:
controllers.js:53 Uncaught ReferenceError: $location is not defined
Thanks before, and have a nice day.
You need to call $location in Controller check below
.controller('LoginCtrl', function($scope, $state,$location, $ionicPopup, AuthService) {
//code........
}
In addition to adding $location to your controller, my guess is you might also need to use the AngularJS $http method (or $post) method instead of $ajax, so that AngularJS knows when your request is completed and handles the scope update.
also change:
var path = $location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
to:
$location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
no need to put in the path var if its not used.
I am merely trying to populate an array from an $http request and display the results in a table. Using Firebug, it seems to me that the data is being retrieved properly. See pictures for results.
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('ContactsController', function ($scope, $http)
{ var self = this; //added after initial post.
this.contactList = [];
this.InitiateContactList = function(arrayContacts) //this.InitiateContactList doesn't work?
{ for(i = 0; i < arrayContacts.length; i++)
this.contactList.push(arrayContacts[i]);
};
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isArray(response.data))
{ //this.contactList = response.data; //is this working properly?
self.contactList = angular.fromJson(response.data);
//this.InitiateContactList(response.data);
}
}, function errorCallback(response) {
});
});
app.controller('ActionsController', function ($scope, $http)
{
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div ng-controller="ContactsController as ContactsCtrl">
<table
<tr><th Email</th>
<th>Name</th>
<th>Frequency</th></tr>
</table>
<div ng-repeat="Contact in ContactsCtrl.contactList">
<table >
<tr><td>{{Contact.Email}}</td><td>test name</td><td>{{Contact.Frequency}}</td></tr>
</table>
</div>
</div>
</body>
</html>
this.contactList = angular.fromJson(response.data); seems to be working. The DOM array is populated as expected, but the ng-repeat doesn't seem to be working. I've done this procedure a couple other times in other contexts and it has worked as expected. What am I missing?
Update: The Batarang extension in Chrome shows the following:
Is it normal to have the index 'Contact' showing like that?
In your ContactsController, do this
var self = this;
Now use self instead of all this in your controller:
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
self.contactList = angular.fromJson(response.data);
});
Hope that helps.
this.contactList = angular.fromJson(response.data);
In this instance, this refers to the function prototype of the anonymous callback function from the then() call. Be careful in Javascript when using the word this in many callbacks and such. Declare a variable, and assign the needed function prototype, and then reference that variable, instead of the reserved, ever-changing this keyword.
I do not know how can i post my data's into a new php page and this is my code:
<ngcart-checkout service="http" settings="{ url:'./checkout.php' }">Checkout </ngcart-checkout>
but the original code from the ngCart docs is
<ngcart-checkout service="http" settings="{ url:'/checkout' }"></ngcart-checkout>
the ngcart-checkout code is
<button class="btn btn-primary" ng-click="checkout()" ng-disabled="!ngCart.getTotalItems()" ng-transclude>Checkout</button>
still it does not redirect me unto checkout.php and so i go to the ngcart.js and the codes for the checkout using http post is
.service('ngCart.fulfilment.http', ['$http', 'ngCart', function($http, ngCart){
this.checkout = function(settings){
return $http.post(settings.url,
{data:ngCart.toObject()})
}
}])
so again my problem was how can i redirect my checkout button unto the checkout.php and how can i post those items unto the checkout.php using http post?
I think perhaps you are looking for something like this in your ngcart.js file
<script>
.service('ngCart.fulfilment.log', ['$http', 'ngCart', function($http, ngCart){
this.checkout = function(settings){
//var item_data = ngCart['$cart']['items'], message;
//return $http.post('checkout.php',
// {data:item_data});
var postData = 'item_data='+JSON.stringify(ngCart['$cart']['items']);
$http({
method : 'POST',
url : 'checkout.php',
data: postData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(res){
console.log(res);
}).error(function(error){
console.log(error);
});
}
}])</script>
I am attempting to make a simple authentication service by sending a Post to a php file, I need it to load the home page partial on my ng-view when its successful.
This is what I tried :
function loginCtrl($scope, $http, $location){
$http.post(url,data).success(function(data){
$location.path('/home');
});
}
Results in my url changing but ng-view not updating. It updates when I manually refresh the page.
(routes have been configured properly at the $routeProvider, I have tested redirecting this with a standalone function not as a callback and it works )
I have also tried defining $location.path('/home') as a function and then calling it on the callback it still doesn't work.
I did some research and found some articles stating this happens when using another third party plugin, I am only loading angular.js
Any insights or pointers to some study material will be great
Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase
//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
$scope = $scope || angular.element(document).scope();
if(forceReload || $scope.$$phase) {
window.location = url;
}
else {
//only use this if you want to replace the history stack
//$location.path(url).replace();
//this this if you want to change the URL and add it to the history stack
$location.path(url);
$scope.$apply();
}
};
There is simple answer in the official guide:
What does it not do?
It does not cause a full page reload when the browser URL is changed.
To reload the page after changing the URL, use the lower-level API,
$window.location.href.
Source: https://docs.angularjs.org/guide/$location
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
Instead of using success, I change it to then and it works.
here is the code:
lgrg.controller('login', function($scope, $window, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$scope.errorInfo = null
$http({
method : 'POST',
url : '/login',
headers : {'Content-Type': 'application/json'}
data: $scope.loginUser
}).then(function(data) {
if (!data.status) {
$scope.errorInfo = data.info
} else {
//page jump
$window.location.href = '/admin';
}
});
};
});
Use : $window.location.href = '/Home.html';
it's very easy code .. but hard to fined..
detailsApp.controller("SchoolCtrl", function ($scope, $location) {
$scope.addSchool = function () {
location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
}
});