AngularJS code hangs browser - javascript

I am calling a Web Service which returns around 3000 records as data entries as HTML response & i am trying to read this response using angularJS.
Below is my AngularJS code i am using to call the service
angular.module('tabApp', ['ngSanitize'])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 0;
$scope.setTab = function(newTab){
$scope.tab = newTab;
$scope.loading = true;
HttpService.CallService('Service.php?id='+newTab,newTab, function (data) {
$scope.myText = data;
$('.count').show();
$("[id^=searchg]").show();
$('.results').show();
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
$scope.setTab1 = function(newTab1){
$scope.tab = newTab1;
$('.loaderImage').hide();
};
$scope.isSet1 = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
$rootScope.loading = true;
return {
CallService: function (url,tabnum, callback) {
$http({
method: "POST",
url: url,
data: {id: tabnum}})
.success(function (data, status) {
$('.loaderImage').hide();
callback(data, status);
}).error(function (data, status) {
$('.loaderImage').hide();
callback(status);
});
}
}
}]);
My problem is the browser hangs if the returned records are more than 1500. Please advise on how i can improve this.
Update:
My html code looks like this
<div ng-show="isSet(1)">
<div id=matches style="display:none"></div>
<input type=text id=searchg placeholder="Type to search..." style="display:none" />
<p class="preload" ng-bind-html="myText"></p>
</div>

As we can see it is the bulky data which you are trying to bind. In Future, it could be more bulky.
You should use the server side pagination and get only the number of records, what your pagination is.
Here is the JSFiddle link for the reference.
http://jsfiddle.net/dwahlin/3Kewg/
Hope this helps! CHEERS TO CODE! :)

As #Mohit Dixit suggested, you should prefer to do server side paging and request only active page records.
I would advise you to use smart table library for this. Here is the official website for same. They support paging(both server side and client side), filter and sorting in one go.
Please note that there are many library available for this purpose but I am suggesting this as I am using it from past few years.

Related

unable to hit the spring controller when tested in IE11

I have a trouble with IE when ng-click is used in the button.
I want to reload the data from spring controller whenever user click on the button which is working fine in chrome but not in IE11.
Issue is when page is loaded data is displayed on the webpage, when Refresh Data button is clicked, it will reload the data by hitting to the spring controller which is not working in IE. In IE, when user click on a button, it is hitting the angular controller as well as service method also but not hitting the spring controller.But when developer tools is opened it is hitting the spring controller.
Example below:
html code:
<div ng-controller="loadingSampleCtrl">
<button class="btn btn-primary" type="button" ng-click="loadOrRefreshData()">Reload</button>
{{myData.empName}} /* This is printed in chrome as well as in IE with developer tools opened*/
</div>
js code:
myApp.controller('loadingSampleCtrl', function ($scope, MyService) {
$scope.loadData = function () {
$scope.loading = true;
MyService.testData().then(
function (response) {
alert("response back from spring controllerf");
if(window.navigator.msSaveOrOpenBlob){
$scope.IEBrowser = true;
$scope.myData = response;
/* $timeout(function() {
$scope.pdfName = response;
}, 0);*/
} else {
$scope.IEBrowser = false;
$scope.myData = response;
}
},
function (errResponse) {
$rootScope.showError("Internal error" + errResponse);
});
}
$scope.testData();
});
//service call
_myService.testData = function(){
alert("service call");//this alert is visible in IE
var deferred = $q.defer();
var repUrl = myAppURL+'/myDataToRead/getData.form';
$http.get(repUrl).then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
deferred.reject(errResponse);
}
);
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/getData", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
List<String> getMyData(HttpServletRequest request) throws Exception {
System.out.println("In MyDataController"); //not printed in IE when tested without developer tools
//logic here
//return statement
}
Any suggestions would be helpful.
i check you url var repUrl = yAppURL+'/myDataToRead/getData.form';, and i this the issue is you are not map controller with the path. you are only map your method with /getData. you need to use #RequestMapping annotation into your controller. you can refer below code :
#RestController
#RequestMapping("/myDataToRead")

http function undefined on angular

I'm new to angular and MEAN stack, and prior to this, I asked a question here:
Angular Routing ngRoute fails to pull my other HTML files
Basically, I didn't properly set my app routing and the solution is I have to modify my link to #! from #, and someone there said that it was caused by breaking change in Angular 1.6, before this I had a working implementation but it wasn't a proper one-page app since it didn't pull only the appropriate HTML of the app. Okay, so now I can view and navigate the app.
Then I ran into another problem when I tried to communicate with the app which supposedly registered me into the app, when I clicked on the button on my HTML page
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
I got an error on the console log, saying
Error: $http.post(...).success is not a function
at b.$scope.register (iotApp.js:73)
at fn (eval at compile (angular.js:15152), <anonymous>:4:144)
at e (angular.js:26673)
at b.$eval (angular.js:17958)
at b.$apply (angular.js:18058)
at HTMLFormElement.<anonymous> (angular.js:26678)
at bg (angular.js:3613)
at HTMLFormElement.d (angular.js:3601)(anonymous function) # angular.js:14324(anonymous function) # angular.js:10834$apply # angular.js:18063(anonymous function) # angular.js:26678bg # angular.js:3613d # angular.js:3601
This is the part of the code indicated by the console where the error is
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
I have read some of the other answers but most of them have accidentally put the dependency in the method parameters where the controller is already imported. It works fine when I use the Advanced REST Client, which is a chrome extension to manually send a register request, but not when I use the app. Any help or just general pointers would be appreciated. Thank you!
From the $http.post documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Getting data from database to angular js

I'm new to Angular JS and I've been learning from codeschool.
I have this problem i can't figure out how to solve: I want to get data from a PHP file that I'm working on but first I wanted to make a short example because something just doesn't make sense to me, and is that can never retrieve the information that has the PHP file to the angular controller.
I have uploaded it on a jsfiddle you can check out if you want.
Here's the html, it's pretty basic:
<div ng-app="app">
<div ng-controller="MyController as c">
<h1>{{c.title}}</h1>
<p>Controller trial: {{c.content}}</p>
</div>
</div>
And here the JavaScript source:
var app = angular.module("app", []);
app.controller("MyController", ['$http', function ($http) {
this.title = "My Title";
var filecontent = "Data should be replaced";
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
filecontent = data;
//I don't know why data is not loaded here :S
});
this.content = filecontent;
}]);
Finally, this is the output i'm getting:
My Title
Controller trial: Data should be replaced
If you visit the link from which i'm retrieving the information you should see this output "You connected to my PHP file", but as i said before, the data seems to never get updated to the variable:
this.content
Thank you so much for all your help!
Juan Camilo Guarin P
Data isn't loaded here, because initially "content" is primitive.
You have two ways: init "content" as object or write smth like this:
var filecontent = "la la la",
that = this;
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
that.content = data;
});
app.controller("MyController", ['$http', '$scope' function ($http,$scope) {
this.title = "My Title";
var filecontent = "Data should be replaced";
$http.get("http://www.otherwise-studios.com/example.php")
.success(function (data) {
filecontent = data;
$scope.content = filecontent; // must be within success function to automatically call $apply
});
}]);

AngularJS Defer.promise not working as expected

I'm developing an application using AngularJS & PersistenceJS.
I'm getting trouble dealing with Asynchronous calls as the
Controller :
cars.controller('CrashWidgetOneCtrl',function($scope, $location, $routeParams, CrashServices){
if($routeParams.crashId){
$scope.data = {};
console.log("CrashID: "+$routeParams.crashId);
crashId = $routeParams.crashId;
alert(1);//Works
CrashServices.getCrashDetails($scope, crashId).then(function(result){
console.log(result);
alert(2);//Never Fires
});
alert(3);//Gets executed
}else{
console.log("N");
}
});
Services :
cars.factory('CrashServices', function($http, $location, $q, CommonServices,$rootScope, $timeout){
return{
getCrashDetails:function($scope, crashId){
var deferred = $q.defer();
// Get user details if any
$scope.$apply(function(){
var crashInfoTable = App.CrashInfoTable.all();
alert(4);
crashInfoTable.list(null, function (results) {
alert(5);//This also doesn't work
deferred.resolve();
});
});
return deferred.promise;
}
}
});
Any help will be greatly appreciated. Many thanks.
Note: I am using PersistenceJS.
I dont know if you need the scope.apply.
This seemed to work for me:
getCrashDetails:function($scope, crashId){
var deferred = $q.defer();
// Get user details if any
App.CrashInfoTable.all().list(null, function(results) {
deferred.resolve(results);
});
return deferred.promise;
}

Scope are not updated AngularJS

I'm sad... I cook porridge of the ax..
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.

Categories