ng-repeat not reflecting when the source variable gets modified - javascript

I have the following angularJs code. When my source data changes, my ng-repeat does not update my view. I looked at other posts and added $scope.$apply(); , $scope.$digest(); at the end of my ajax success callback, but it did not help. The idea is that the page will have an empty table in the begining and after the ajax call onReady() it will populate the rows with data. Could someone point me at what I am missing here or a better way to achieve the same
JS:
(function() {
var app = angular.module("jmeter-module", []);
app.controller('JmeterTableController', ['$scope', function($scope){
$scope.data = [];
$(document).ready(function(){
var url = "jmeterTableData.html";
fetchTableData(url, 10, 25);
});
function fetchTableData(url, minAge, maxAge){
$.ajax({
type: "GET",
url: url,
data: { minAge : minAge,
maxAge : maxAge },
datatype: "json",
success: function(data){
/*If I try to print data here, I see the values rightly getting returned*/
$scope.data = data;
},
error: function(e){
console.log(e);
}
});
}
}]);
})();
JSP:
<div id="buildGroupsParentDivId" ng-controller="JmeterTableController as row">
.
.
.
<tbody id="jmeter-table-content" >
<tr ng-repeat="val in row.data">
<td><img title="History" src="/images/history.png" width="20" height="20"></td>
<td><input type="checkbox" value="save"></td>
<td>{{val.firstName}}</td>
<td>{{val.lastResult}}</td>
</tr>
</tbody>

the problem is with the execution of $.ajax outside of the scope of Angular's digest cycle. You could get this working with $scope.$apply, but since you're already using Angular it's better to use the AngularJS xhr helper methods:
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Related

issue while printing the variable to html page

I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed
this is my html:
<div ng-app="app" ng-controller="VolController">
<div class="account-action">
<h3 style="display:inline;"><img class="img" align="left" src="images/u11.png">
<p style="color:white"> Welcome {{first_name}}<p></h3>
</div>
this is my controller:
app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){
var b=sessionStorage.getItem("userid");
var a="http://localhost:8080/volunteers/"+b;
$.ajax({
type:'GET',
url:a,
success:function(data){
console.log(JSON.stringify(data));
$scope.volunteer=data;
$scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
console.log(data);
},
error:function(data){
alert(data);
},
dataType:"json",
contentType:"application/json",
})
}]);
Question Updated!!!!
As you use $.ajax instead of native $http, you should wrap assigning into $apply:
success: function(data) {
$scope.$apply(function(){
$scope.volunteer = data;
$scope.first_name = JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
});
}
You should use $scope,
$scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
Don't make ajax call using jquery $.ajax. Please make ajax call using $http service of angularjs.
$http.get(url);
Do not forget adding $http service as dependedency in angular.

Convert jQuery post with callback functions to angular $http

I have a angular controller that has a function which adds the html retrieved in post to a container. I can then click on a div within that sets a var result to some data onclick.
<div onclick="var result = {"some":"data", "right":"here"}...
The issue Im having is retaining the callback functions functionality. This is what I am trying to convert.
jQuery.post(url, {
'callback': "callbackFunctions.setData(result);callbackFunctions.closeDialog();",
'return_type' : 'json'
},
function (json) {
if (json.success) {
jQuery('#template').html(json.message);
}
}, 'json');
That snippet is currently using a external set of functions from the angular controller.
var callbackFunctions = {
closeDialog: function () {
angular.element('#template').dialog('close');
},
SetData: function (result) {
var scope = angular.element('.variables img:visible').scope().$parent;
scope.$apply(function(){
jQuery.extend(true, scope.variables, {
url: result.url,
name: result.name,
thumbnail: result.thumbnail,
value: result.url
});
});
}
};
I just don't think this is the cleanest solution. It currently works I just cant seem to convert this to angular's $http request and get the callback functions to work. Ideally this would be $http.post and when calling the functions they would be within the controller so I already have access to the scope.
One gotcha I can not modify the http I am requesting its used in a ton of other areas of the site not yet updated.
Controller
$http.post(url, data).then(function(response){
$scope.message = response.message;
}, function(error){
console.log("Error detected : " + error);
})
HTML
<div id="template">
{{message}}
</div>
I don't really know what you want to do with the API's data but you can use ng-bind or {{variable}} inside your html to display them

Displaying the contents of ng-controller after calling AJAX with the "as" function

What I'm trying to show the contents of ng-repeat after calling AJAX (i.e. $http)
<table ng-controller="TableController as tc">
<tr>
<th>Date</th>
<!-- other headers are here -->
</tr>
<tr ng-repeat="order in tc.orders" >
<td ng-bind="order.id"></td> //It doesn't appear
<td>#{{ order.id }}</td> //It doesn't appear as well. I use Laravel, so I need to put #
</tr>
</table>
Here is the relevant script part
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
this.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
this.orders = response.data;
console.log("Inside; "+this.orders.length);
});
});
From console.log("Inside; "+this.orders.length), I can see that the expected data was assigned to this.orders array. However, as the title of this post suggests, the array is not displayed with ng-repeat="order in tc.orders".
I followed this question, but following this did not solve this issue. Now I suspect that the cause lies in the as statement, which I have to use for this occasion.
As I don't see many information resources about the as online, I'd appreciate if you'd give any advice.
you should use your instance inside promise resolved function
to assign to the right instance (controller instance) :
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
instance.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
instance.orders = response.data;
console.log("Inside; "+ instance.orders.length);
});
});
its usual to name this instance : vm refers to View Model
Example:
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var vm= this;
vm.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
vm.orders = response.data;
console.log("Inside; "+vm.orders.length);
});
});

Issue in populating ajax data into table via ng-repeat

I am trying to populate a table on receiving JSON data on an Ajax get from Mongo DB.
I am able to see the received data in alert. But my table is not populated.
I am clicking the retrive button to get the data.
JS code:
$scope.retrive = function()
{
$scope.people =[];
$.ajax({
url : "https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=veTqID_gkb74tG-yL4MGcS1p2RRBP1Pf",
type : "GET",
dataType: "json",
success: function(data) {
$scope.people = JSON.stringify(data);
alert($scope.people);
//alert("status = "+data.status+"descripttion"+data.description);
//console.log(data);
//document.getElementById("n1").innerHTML = data[0].name;
//alert(JSON.stringify(data));
tableCreate(data);
//alert(data[0].name);
//var json = JSON.parse(data);
//alert(json.name);
}
});
};
}]);
HTML code:
<div>
<table>
<tr>
<th>ITEM</th>
<th>DESCRIPTION</th>
<th>QUANTITY</th>
<th>LOCATION</th>
<th>CATEGORY</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.Item}}</td>
<td>{{person.Description}}</td>
<td>{{person.Quantity}}</td>
<td>{{person.Location}}</td>
<td>{{person.Category}}</td>
</tr>
</table>
</div>
Here is the Plunker Link :
http://plnkr.co/edit/OKzTApbW7ii8R0EMrOyx?p=preview
Try is like this:
Note (Just a tip ): Putting API keys within stack overflow questions is not a good idea. Keep the API key private as any body can use your key and you could blocked out from the service due to unauthorised usage.
var myApp = angular.module('myApp', []);
myApp.controller('projectController', function($scope, $http){
$scope.userDetails = [];
$scope.test = function(){
console.log("getting user projects, please wait ......");
// Simple GET request example (passing data) :
$http.get("https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=YOUR-API-KEY", {
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("");
$scope.userDetails = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Heres a working Plunker:
http://plnkr.co/edit/xoFuBa695E7O1g6gTcm4?p=preview
UPDATED Plunker
http://plnkr.co/edit/7E4PKbnqBDwsVptIaJ1Q?p=preview

AngularJS: display a select box from JSON data retrieved by http GET (from REST service)

I have a REST service that I made which returns a json string which is simply a set of strings (I used Gson to generate this string (Gson.toJson(mySetOfStrings))
So I have added to my index.html:
<div ng-controller="ListOptionsCtrl">
<form novalidate>
<button ng-click="refreshList()">refresh</button>
<select name="option" ng-model="form.option" ng-options="o.n for o in optionsList></select>
</form>
</div>
and in my script:
var ListOptionsCtrl = function ListOptionsCtrl($scope, $http) {
$scope.refreshList = function() {
$http({
method: 'GET'
url: '*someurl*'
}).
success(function(data) {
$scope.optionsList = angular.fromJson(data);
});
};
}
Unfortunately all this produces in my select box is an empty list. When I see what the response to the GET request is it returns a json string with content in it so I do not see why nothing is being added to this element. What am I doing wrong here? thanks
It is because Angular does not know about your changes yet. Because Angular allow any value to be used as a binding target. Then at the end of any JavaScript code turn, check to see if the value has changed.
You need to use $apply
var ListOptionsCtrl = function ListOptionsCtrl($scope, $http) {
$scope.refreshList = function() {
$http({
method: 'GET'
url: '*someurl*'
}).
success(function(data) {
$scope.$apply(function () {
$scope.optionsList = angular.fromJson(data);
});
});
};
}
Try this.
More about how it works and why it is needed at Jim Hoskins's post
You should check for $digest error by doing if(!$scope.$$phase) { ... } before doing $apply.
success(function(data) {
if(!$scope.$$phase) {
$scope.$apply(function () {
$scope.optionsList = angular.fromJson(data);
});
}
});

Categories