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.
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 am new to AngularJS and need to use AngularJs to render my MVC controller Json output. Below is my MVC Controller that output Json:
[HttpGet]
public JsonResult GetAllData()
{
int Count = 50;
return Json(Workflow.Teacher.GetTeachers(Count), JsonRequestBehavior.AllowGet);
}
My Angular Controller that calls the GetAllData Action method:
angular.module('myFormApp', [])
.controller('HomeController', function ($scope, $http, $location, $window) {
$scope.teacherModel = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
$scope.ListTeachers = null;
getallData();
//******=========Get All Teachers=========******
function getallData() {
$http({
method: 'GET',
url: '/Home/GetAllData'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers = response;
console.log($scope.ListTeachers);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!';
console.log($scope.message);
});
};
})
.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
Further my MVC layout markup is bellow:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Teachers List</h2>
<div id="content" ng-controller="HomeController">
<span ng-show="isViewLoading" class="viewLoading">
<img src="~/Content/images/ng-loader.gif" /> loading...
</span>
<div ng-class="result">{{message}}</div>
<table class="table table-striped">
<tr ng-repeat="teacherModel in ListTeachers">
<td>{{teacherModel.TeacherNo}}</td>
<td>{{teacherModel.TeaFName}}</td>
<td>{{teacherModel.TeaSName}}</td>
</tr>
</table>
</div>
#section JavaScript{
<script src="~/Scripts/angular.js"></script>
<script src="~/ScriptsNg/HomeController.js"></script>
}
further to above my main layout's body tag also have ng-app
<body ng-app="myFormApp" >
I am using MVC version 5 with AngularJs v1.6.4.
On debugging I can confirm that it does call getallData() actionMethod and does return rows in Json. I am not getting any error but its not rendering the model values either.
Any suggestions would be appreciated.
use response.data to catch the data.
change
$scope.ListTeachers = response;
to this
$scope.ListTeachers = response.data;
You have a number of problems with this code. Firstly, by assigning
$scope.ListTeachers = null;
you are making it more complicated to work with this variable later. If you expect REST interface to return you an array, then it is fine to make initial assignment as an empty array.
$scope.ListTeachers = [];
It is important because you should not override this object when you get a new result back. Angular adds its own magic to objects it is bound to, and by overriding an object you destroy that magic.
How you should update the data is something like this this:
then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers.length = 0;
if( response && response.data){
response.data.forEach(function callback(currentValue)
{
$scope.ListTeachers.push(currentValue);
});
}
console.log($scope.ListTeachers);
}
I hope this helps.
Then callback response has several parameters like data , headers, status , statustext to check your request.
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'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
I am trying to use breeze to do the same calls that work using angualar's $http. For some reason the $scope does not appear to work in the breeze callback.
Code:
<!DOCTYPE html>
<html ng-app="">
<head>
<meta name="viewport" content="width=device-width" />
<title>App</title>
</head>
<body ng-controller="TextController">
<div>
<p>{{textData1}}</p>
<p>{{textData2}}</p>
<ul>
<li ng-repeat="patient in patients">
<span>{{patient.FirstName}}</span>
</li>
</ul>
</div>
<script src="/scripts/jquery-1.8.2.js"></script>
<script src="/scripts/q.js"></script>
<script src="/scripts/breeze.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
function TextController($scope, $http){
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
var serviceName = "/api/breeze";
var manager = new breeze.EntityManager(serviceName);
var query = breeze.EntityQuery.from("Patients");
$scope.textData1 = "Waiting..";
$scope.textData2 = "Waiting..";
manager.executeQuery(query).
then(function (data) {
console.log(data);
$scope.textData1 = 'Breeze';
//$scope.patients = [];
//$scope.patients = data;
}).
fail(function(error) {
$scope.textData1 = error.message;
});
$http({ method: 'GET', url: '/api/patients' }).
success(function (data, status, headers, config) {
console.log(data);
$scope.textData2 = 'Angular';
//$scope.patients = [];
//$scope.patients = data;
}).
error(function (data, status, headers, config) {
});
}
</script>
</body>
</html>
In the above code both the angular $http call and the breeze calls return data as I print it to the console. When this is run only the textData2 binding updates to 'Angular' the textData1 binding does not update to 'Breeze'. I'm in the function as the console gets called but the binding does not update. The same thing happens if I try to bind the list of data the the 'patients' reference in the scope. I commented that out to show the simplest version of my problem.
Make sense? Thoughts?
Brian