I have got code that reads the data from the array perfectly when I use a AJAX request. When I push an object to the array however, ng-repeat doesn't render the new row and I have to refresh the page to then fetch the data that was sent to server.
Why does it do this?
Thanks
Javascript
function processError() {
var responseCode = 404;
var error = {};
error["client"] = document.getElementById('client').value;
error["errorMessage"] = document.getElementById('error-message').value;
error["simpleRes"] = document.getElementById('simple-fix').value;
error["fullRes"] = document.getElementById('full-fix').value;
error["reason"] = document.getElementById('reason').value;
var errorJson = JSON.stringify(error);
$.ajax({
url: "../ErrorChecker/rest/error",
type: "POST",
data: errorJson,
contentType: "application/json"
})
.done(function (data, statusText, xhr, displayMessage) {
$('.form').hide();
responseCode = xhr.status;
reloadData(data);
});
function reloadData(data) {
if (responseCode == 200) {
processPositiveResponse(data);
} else {
$('#negative-message').show(1000);
}
}
}
function processPositiveResponse(data) {
$('#positive-message').show(1000);
updateTable(data);
$('#errorTable').DataTable().destroy();
setupTable();
clearInputs();
console.log($scope.controller.errors);
}
function updateTable(data) {
$scope.controller.errors.push({
"id": data,
"client": document.getElementById('client').value,
"errorMessage": document.getElementById('error-message').value,
"simpleRes": document.getElementById('simple-fix').value,
"fullRes": document.getElementById('full-fix').value,
"reason": document.getElementById('reason').value
})
}
HTML
<tbody>
<tr ng-repeat="x in dataCtrl.errors">
<td class="collapsing">
<div class="ui toggle checkbox">
<input type="checkbox">
<label></label>
</div>
</td>
<td style="display: none">{{ x.id }}</td>
<td>{{ x.client }}</td>
<td>{{ x.errorMessage }}</td>
<td>{{ x.simpleRes }}</td>
<td>{{ x.fullRes }}</td>
<td>{{ x.reason }}</td>
</tr>
</tbody>
That's because you're using jQuery and Angular together. Don't do that. EVER. Angular is not aware of what jQuery is doing, and jQuery is not aware of what Angular is generating in the DOM. Solution : REMOVE jQuery and use Angular's own $http service.
The same way, don't use document.getElementById('full-fix').value. You're taking Angular backwards. Angular generates the DOM from data, so you don't need to select DOM elements to read their value because that value is already in your data.
Update the document. Use scope apply as a quick fix. Not the way to do it imo. But it will solve your problem fast. On my mobile if I do not forget ill update this comment later with more details and best practises. For now a google search to scope apply will help you a long way.
Related
Im using AngularJS on front-end and PHP on back-end that is hosted in Google App Engine. Now when i try to fetch JSONP data directly from server it goes fast, when i use a Google service the time increases with almost 1s. Very short: Im getting my data very slow, it takes 1.3-1.8s to render data on screen.
This is my Client-code-Controller:
angular
.module('RDash')
.controller('tables-ctrl5', ['$scope','$http', function($scope,$http) {
$http({
method: 'jsonp',
url: 'https://gtmdocx.appspot.com/test5?callback=JSON_CALLBACK',
headers: {"Content-Type":"application/json"}
}).then(function ListCtrlresponses(response) {
$scope.GTMWorkspacesTags = response.data.tag;
console.log(response.data.tag);
$scope.GTMWorkspacesTagsLength = response.data.tag.length;
}, function Error(response) {
$scope.users = response.statusText;
});
}])
im using ng-repeat:
<div class="col-lg-6">
<rd-widget>
<rd-widget-header icon="fa-tasks" title="Google Tag Manager - URL: http://gtmdocx.appspot.com/test3 (LISTE AV TAGS I WORKSPACE) = Hent ut PATH fra LISTE av Workspace (EX: accounts/1746756959/containers/7454209/workspaces/8)">
</rd-widget-header>
<rd-widget-body classes="medium no-padding">
<div class="table-responsive">
<table class="table table-striped" ng-controller="tables-ctrl5">
<thead>
<tr>
<th>AccountID</th>
<th>ContainerID</th>
<th>TagName</th>
<th>Path</th>
<th>test</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="workspace in GTMWorkspacesTags">
<td>{{ workspace.accountId }}</td>
<td>{{ workspace.containerId }}</td>
<td>{{ workspace.name }}</td>
<td>{{ workspace.path }}</td>
<td>{{GTMWorkspacesTagstest}}</td>
</tr>
</tbody>
</table>
</div>
</rd-widget-body>
<rd-widget-footer>
Footer
</rd-widget-footer>
</rd-widget>
</div>
Now this is my PHP-code: very simple and straight forward: (PS: using slim)
// 4) Gets all TAGS related to this WORKSPACE
$app->get('/test5', function (Request $request, Response $response) {
$client = new Google_Client();
$client->setApplicationName("gtmdocx");
$client->setAuthConfig('service_account.json');
$client->setScopes(['https://www.googleapis.com/auth/tagmanager.readonly',
'https://www.googleapis.com/auth/tagmanager.manage.accounts',
'https://www.googleapis.com/auth/tagmanager.edit.containers',
'https://www.googleapis.com/auth/tagmanager.publish'
]);
$service = new Google_Service_TagManager($client);
$containers = $service->accounts_containers_workspaces_tags->listAccountsContainersWorkspacesTags('accounts/1746756959/containers/7454209/workspaces/8');
echo $_GET['callback'] . '('.json_encode($containers).')';
});
If you look at the timing on response:
I hope someone has experienced this before. This is really bothering me that it is using so much time to render. When i type in directly the URL in browser i get response right away, but in angularjs as front its slow. Im using JSONP to fetch because of CORS, can this be the problem?
I am developing my first angular-app with an .Net backend.
I get my data async from a webmethod using a http.post. That all works fine.
Client-side I would like to do some simple calculations (a final row in a table which contains sums of all the data in table)
The code to do this is pretty straight forward but my problem is the data i not ready when I try to do it.
I have read that I could use a promise and a service or a factory. But I am not sure what we be the best way to go.
My code for the view:
<div ng-controller="taskCtrl as ctrl">
<div class="col-md-10 container outer">
<h1 class="center-block">{{ctrl.SprintViewModel.SprintName}}</h1>
<table id="SprintMetaDate">
<tr><td>Projekt:</td><td>{{ctrl.SprintViewModel.ProjektName}}</td></tr>
<tr><td>Periode:</td><td>{{ctrl.SprintViewModel.StartDate}} - {{Ctrl.SprintViewModel.EndDate}}</td></tr>
<tr><td>Udarbejdet af/d:</td><td>{{ctrl.SprintViewModel.MadeBy}}</td></tr>
</table>
<h3>Sprint Resume:</h3>
<br/>
{{ctrl.SprintViewModel.SprintResume}}
<h3>Sprint afslutning:</h3>
{{ctrl.SprintViewModel.SprintDemo}}
<h2>Scope og Økonomi </h2>
<h3>Sprint Opgaver</h3>
<table id="SprintTasks" class="col-md-12">
<tr><th>Opgave</th><th>Estimat</th><th>Forbrug</th><th>Udest.</th><th>*</th><th>Pris (DKK)</th></tr>
<tr ng-repeat="x in ctrl.SprintViewModel.Tasks">
<td style="width: 40%">{{ x.Description }}</td>
<td>{{ x.TimeEst }}</td>
<td>{{ x.TimeUsed }}</td>
<td>{{ x.TimeRemaining }}</td>
<td>{{ ctrl.CalcPrecisionOfEstimat(x.TimeUsed,x.TimeRemaining,x.TimeEst) | number:2}} %</td>
<td>{{x.Price}}</td>
</tr>
<tr>
<td>Ialt</td>
<td>{{ ctrl.TotalEstimat() }}</td>
<td>{{ ctrl.TotalTimeUsed() }}</td>
<td>{{ctrl.TotalTimeRemaining()}}</td>
<td>{{ctrl.TotalPrecision()}}</td>
<td>{{ctrl.TotalPrice()}}</td>
</tr>
</table>
* Forbrug + Udestående i forhold til estimat
<br/>
Udestående opgaver er planlagt ind i næstkommende sprint.
</div>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('taskCtrl', function($scope, $http) {
var ctrl = this;
ctrl.SprintViewModel = null;
ctrl.TotalEstimat=function() {
var totalEstimat=0;
for (i=0; i<ctrl.SprintViewModel.Tasks.count;i++) {
totalEstimat += ctrl.SprintViewModel.Tasks[i].Estimate;
}
return totalEstimat;
}
ctrl.TotalPrecision = function () {
var totalPrecision=0;
angular.forEach(ctrl.SprintViewModel.Tasks, function (value, key) {
totalPrecision += Number(value);
});
$http.post('SprintRapport.aspx/GetSprintViewModel', {})
.then(function(response, status, headers, config) {
console.log("I success");
ctrl.SprintViewModel = response.data.d;
});
});`
As already mentioned I get a nullreference every when the page-load on all the methods in the last row, because ctrl.SprintviewModel is undefined. I have only included one of the methods for simplicity, the problem is the same for all of them.
So my question is how do I make sure that ctrl.TotalEstimat() first get called then ctrl.SprintViewModel is assigned?
You can add ng-if condition to the last <tr> which resolves to true when data is ready to populate in your controller. So you can define $scope.loading = false initially and once your code is ready to populate you set $scope.loading=true and that will call $digest cycle internally and your view gets updated.
There are several things that you could do. I've fixed this kind of issue by placing guard conditions in the functions. These check that the necessary variables have been set before continuing. So adding if (!ctrl.SprintViewModel) return; at the beginning of the function as follows:
ctrl.TotalEstimat=function() {
// Guard Condition to prevent function executing in invalid state.
if (!ctrl.SprintViewModel) return;
var totalEstimat=0;
for (i=0; i<ctrl.SprintViewModel.Tasks.count;i++) {
totalEstimat += ctrl.SprintViewModel.Tasks[i].Estimate;
}
return totalEstimat;
}
It's another option, but as you have already alluded to, I think that promises and the $q library is the proper angular way to fix this sort of thing.
I know there are many questions already posted for the same issue but none of the solutions work in my case.
On calling a web service I get JSON response. In this JSON, there are around 2000+ objects from which I need to display data on the table. I want to display all (2000+) records in the table and Yes, I cannot limit or paginate, need to display it on a single page (I know it's stupid but it's the business requirement). I don't need sorting or searching.
Data transfer is about 2MB and the request completes in about 2-4 secs approx. but it takes around 10-15 secs to data render on the page.
Now, what I am looking for is either speed ng-repeat binding things up (if possible) or display the data as soon as I receive it and keep on adding it until all rows are displayed.
Check out the code below :
HTML
<table class="table table-bordered table-striped cf">
<thead style="color: #333;">
<tr>
<td>Asset Name</td>
<td>Date/ Time</td>
<td>Location</td>
<td>Ignition</td>
<td>Speed</td>
<td>Heading</td>
<td>Direction</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="cols in tableData">
<td>{{ cols.aN }}</td>
<td>{{ cols.dT }}</td>
<td>{{ cols.Lat }}, {{ cols.Lon }}</td>
<td>{{ cols.I }}</td>
<td>{{ cols.S }}</td>
<td>{{ cols.H }}</td>
<td>{{ cols.D }}</td>
</tr>
</tbody>
</table>
JS
var ignition_text = '';
var lat = '';
var lon = '';
for (var i = 0; i < data.length; i++) {
if (data[i].ignition = 1) {
ignition_text = "On";
} else {
ignition_text = "Off";
}
$scope.$apply(function() {
$scope.tableData.push({
aN: name,
dT: data[i].eventUTCTime,
Lat: data[i].latitudeDegrees,
Lon: data[i].longitudeDegrees,
I: ignition_text,
S: data[i].speedMPH,
H: data[i].longitudeDegrees,
D: data[i].latitudeDegrees
});
});
}
Thanks in advance!
You probably wont need $scope.$apply at all. And even if you need it, you should only use it once you pushed all data to the table. Otherwise, every added entry will force an digest-cycle. Just build your array and assign the finished array to the scope-variable. Then angular will only build the table once.
Depending on the nature of your variable name you may be able to eliminate the array building as well and just use the data you are downloading. Apart from nameyou just use that data anyway.
Here is a plunk that has a similar data size but loads much faster http://plnkr.co/edit/I4rN1ZMaR3e1mbcsJ9Ka. If you were to make a quick plunk I could use your data and edit your code but from the looks you just need the main assignment to the scope without the apply for the data and add a track by to the ng-repeat. SN: You would want to manipulate your data inside the for loop then do the assignment to the scope.
for (var i = 0; i < data.length; i++) {
if (data[i].ignition = 1) {
ignition_text = "On";
} else {
ignition_text = "Off";
}
}
$scope.tableData=data;
JS
$http.get("largeData.json").then(function(response) {
vm.test = response.data;
});
HTML
<tbody>
<tr ng-repeat="(key, value) in main.test track by $index ">
<td>{{ value.ask }}</td>
<td>{{ value.bid }}</td>
<td>{{ value.volume_btc }}, {{ value.volume_percent }}</td>
<td>{{ value.last }}</td>
<td>{{ value.timestamp }}</td>
</tr>
</tbody>
What I'm trying to make is an angular app that reads in a json file and displays them, and allows users to edit the json file using html controls. Then, the user can create a new json object based on their selections and display it.
Here is a picture to help describe what I'm trying to do:
So, the user sees this, they make certain selections, e.g. lock them or delete them, then they hit create, and a new json file is returned based on which objects they have chosen to lock or delete.
At the moment I just have a standard angular app which gets and displays the json:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php").then(function (response) {
$scope.myData = response.data.records;
});
$scope.createJson = function(){
// Create new json file
};
});
The body of my html/my angular app looks like this at the moment:
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in myData">
<td>{{ x.Name }}</td>
<td>{{ x.City }}</td>
<td>{{ x.Country }}</td>
<td><input type="checkbox" name="lock" value="{{x.Name}}"></td>
<td><input type="checkbox" name="delete" value="{{x.Name}}"></td>
</tr>
</table>
<button ng-click="createJson()">Create</button>
</div>
Baiscally, I'm not sure if my approach is correct at the moment, and if it is, I don't really know what my next step is.
P.S. this is just test data I am using for the sake of learning/testing, it is not my data, I got it from: http://www.w3schools.com/angular/customers.php
You can try
JSON.stringify($scope.myData)
or
angular.toJson($scope.myData)
this will give you string representation of your data object. The rest is up to you, you may assign it to textarea, post it back to server (in this case, you most likely won't even need to encode it before) etc.
You should use
<td><input type="checkbox" name="lock" value="{{x.Name}}"></td>
<td><input type="checkbox" name="delete" value="{{x.Name}}"></td>
as
<td><input type="checkbox" name="lock" ng-model="x.Name"></td>
<td><input type="checkbox" name="delete" ng-model="x.Name"></td>
(Actually I didn't understand why you use string in checkbox. It should be boolean value).
By this way any change will change your $scope.myData.
On create you should take info from user and create a new JsonObject like
var newObject = {
Name: 'Name Surname',
City: 'City',
Country: 'Country'
}
And add this to your myData with;
$scope.myData.push(newObject);
I ended up creating an appropriate solution by simply creating a new and empty JSON object:
var newJson = [];
and populating it by looping through my original one and using array.push() to add the selected entries:
for (var person in $scope.myData){
if($scope.myData[person].Delete === false || $scope.myData[person].Lock === true){
newJson.push($scope.myData[person])
}
}
Consider this conroller
$scope.transaction = {};
$scope.transactions = Transaction.query();
$scope.save = function() {
var transaction = new Transaction();
transaction.name = $scope.transaction['name'];
transaction.debit = $scope.transaction['debit'];
transaction.date = $scope.transaction['date'];
transaction.amount = $scope.transaction['amount'];
transaction.category = $scope.transaction['category'].uuid;
//noinspection JSUnresolvedFunction
transaction.$save();
$scope.transactions.push(transaction);
console.log('transaction saved successfully', transaction);
};
and this HTML
<tbody ng-repeat="transaction in transactions | orderBy: transaction.created_on">
<td>{{ transaction.name }}</td>
<td>{{ transaction.amount | currency }}</td>
<!-- custom filter to display type of transaction -->
<td>{{ transaction.debit | transactionType }}</td>
<!-- added dateInMillis to pass to date to filter Angular way -->
<td>{{ transaction.created_on | dateInMillis | date: 'medium'}}</td>
<td>{{ transaction.category.name }}</td>
<td>
</tbody>
Problem
When I add transaction, it immediately displays bunch of NaNs and then once the server comes back with saved data, it replaces those NaNs with actual data
How can I prevent that from happening? Its not a good UX
Without seeing all the code related to the Transaction object its hard to know for sure what the problem could be. At a glance I think you need a callback function attached to transaction.$save() method.
transaction.$save(function(u, putResponseHeaders) {
// This is $save's success callback
$scope.transactions.push(transaction);
console.log('transaction saved successfully', transaction);
});