Ionic Infinite Scroll with http.post results - angularjs

I am trying to create an infinite scroll based on Gajotres post (http://www.gajotres.net/ionic-framework-tutorial-11-infinite-scroll/)
My problems are:
If i write : $scope.searchObjects($scope.formData); all $scope objects are printed on the screen, how can it be avoided?
Can i pass form data by using $scope.formData, this way: .
$scope.searchObjects($scope.formData);
Until now the list freezes with 7000 itens and can not get the infinite scroll to work , seems it load all the itens.
There is a better know solution to ionic infinite scroll with http.post ?
Here is my attempt code any help would be apreciated :
.controller('someObjectsCtrl', function( $scope, $http) {
$scope.data = null;
$scope.itens = [];
$scope.data = {
'state' : '',
'city' : '',
}
$http.get('http://someservice.com/states.php').then( function response(response){
$scope.states = response.data;
},function(error){
$scope.error = JSON.stringfy(error);
});
$scope.getCities = function(id) {
$http.get('http://someservice.com/state.php?stateid='+id).then( function response(result) {
$scope.cities = result.data;
$ionicLoading.hide();
},function(error) {
$scope.error = JSON.stringfy(error);
});
};
$scope.originForm = angular.copy($scope.data);
$scope.searchObjects = function(data) {
$scope.formData = {};
$scope.formData.state = data.state;
$scope.formData.city = data.city;
$http.post("http://someservice.com/objectsToSearch.php", $scope.formData )
.success( function(data) {
$scope.result = data;
for (var i = 0; i <= 6; i++) {
$scope.itens.push({ foundObjects: $scope.result.OBJECTS});
}
$scope.$broadcast('scroll.infiniteScrollComplete');
if( $scope.result.length == 0 ){
$scope.data = null;
}
$scope.headers = ['Some Objects', 'Another Objects' ];
})
.error(function(error){
$ionicLoading.show({ template: '<p>Error ...</p>',duration :6000 });
})
}
$scope.canWeLoadMoreContent = function() {
return ($scope.itens.length > 10) ? false : true;
console.log(' scope.itens.length '+$scope.itens.length );
}
$scope.searchObjects($scope.formData);
})

Until now the only solution i find was to use collectio-repeat instead of ng-repeat. Collection-repeat is very fast rendering the result list.

Related

JSON won't save on scope AngularJS

i have a problem with saving JSON on a scope, I have already a function saving a JSON into a scope and works perfectly but the second one won't save...
servicoLeituraPosts.php returns JSON with data
servicoLeituraComments.php returns JSON with data
both send JSON through URL correctly, and the first shows data on scope, but the second one doesn't and it's done exactly like the first one, so I don't understand what is going on.
1st one saves JSON into $scope.posts, it has data and i can print it
2nd one saves JSON into $scope.comments, if i print it, it is blank? Why? Thank you for help but I'm a beginner in AngularJS.
<script>
var app = angular.module('postsApp', []);
var interval;
app.controller('postsCtrl', function($scope) {
$scope.toggle = false;
$scope.texto = [];
$scope.comment = [];
$scope.comment = "";
$scope.comments = [];
$scope.posts = [];
$scope.texto = "";
$scope.idPost = 0;
$scope.showBox = function(p){
p.toggle = !p.toggle;
if(interval == 0){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
}else{
clearInterval(interval);
interval = 0;
}
$scope.servicoLeituraComments(p);
console.log($scope.comments);
console.log($scope.posts);
};
$scope.iniciaTimer = function(){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
};
$scope.servicoLeituraPosts = function(){
$.getJSON(
"servicoLeituraPosts.php",
{
},
function(jsonData)
{
$scope.posts = jsonData;
$scope.$apply();
});
};
$scope.servicoLeituraComments = function(p){
$.getJSON(
"servicoLeituraComments.php",
{
"idPost": p.idPost
},
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
});
console.log($scope.comments);
};
$scope.addPost = function(){
$.post(
"addPostRest.php",
{
"texto" : $scope.texto
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addLike = function(idPost){
$.post(
"addLike.php",
{
"idPost" : $scope.idPost = idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addComment = function(p){
$.post(
"addComentarioRest.php",
{
"comment" : p.comment,
"idPost" : p.idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
});
</script>
Found the solution, apparently there was a problem with the parameter recieved on POST which made the JSON invalid having no data
It looks like you are calling console.log($scope.comments); synchronously after calling $.getJSON(...), rather than waiting for the jsonData to be returned. At this point the $scope is yet to be updated.
Try moving the console.log into the callback:
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
console.log($scope.comments);
});

ngResourc:generate unique number

I'm trying to post new data comment and I want $resource serviceto give every comment unique id automatically.but I don't know how to do it . the data was past but in id was property empty ,it don't have id number.
Code for controller.js
.controller('ContactController', ['$scope','FeedbackFactory', function($scope,FeedbackFactory) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" ,id:""};
var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];
$scope.channels = channels;
$scope.invalidChannelSelection = false;
$scope.fback= FeedbackFactory.putFeedback().query(
function(response){
$scope.fback = response;
},
function(response) {
$scope.message = "Error: "+response.status + " " + response.statusText;
}
);
}])
.controller('FeedbackController', ['$scope', 'FeedbackFactory',function($scope,FeedbackFactory) {
$scope.sendFeedback = function() {
console.log($scope.feedback);
if ($scope.feedback.agree && ($scope.feedback.mychannel === "")) {
$scope.invalidChannelSelection = true;
console.log('incorrect');
}
else {
$scope.invalidChannelSelection = false;
$scope.fback.push($scope.feedback);
FeedbackFactory.putFeedback().save($scope.fback);
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.feedback.mychannel="";
$scope.feedbackForm.$setPristine();
console.log($scope.feedback);
}
};
}])
service.js
.service('FeedbackFactory',['$resource','baseURL',function($resource,baseURL){
this.putFeedback = function(){
return $resource(baseURL+"feedback/",{'update':{method:'POST'}});
};
} ])
;
note:the data comment will save in form of JSON data.

Angularjs State transition

I am building a hybrid mobile app using ionic framework and cordova (first time).I am having problems with state transition because by default angular renders the template before completing the transition.This makes the the app look slow (when you click a menu item and wait for it to come).This happens only for those who load data from local storage or service! My Question is: How can I make the template come empty in the moment I click the menu item , then show a loader until the template is ready.Below is some code is use in my menu controller for the state transition!
//I use ng-click="navigateTo('state name')"
$scope.navigateTo = function (stateName) {
$timeout(function () {
$mdSidenav('left').close();
if ($ionicHistory.currentStateName() != stateName) {
$ionicHistory.nextViewOptions({
disableAnimate: false,
disableBack: true
});
$state.go(stateName);
}
}, ($scope.isAndroid == true ? 1000 : 0));
};// End navigateTo.
Below is the controller code for the view that needs a solution
appControllers.controller("calendar_Ctrl", function($scope,$rootScope, $state,$stateParams, $ionicHistory, $filter, $q, $timeout, $log, MaterialCalendarData, $moment) {
$scope.isAnimated = $stateParams.isAnimated;
$scope.selectedDate = null;
$scope.weekStartsOn = 0;
$scope.dayFormat = "d";
$scope.disableFutureDates = false;
$scope.directionn = "horizontal";
$scope.setDirection = function(direction) {
$scope.directionn = direction;
$scope.dayFormat = direction === "vertical" ? "EEEE, MMMM d" : "d";
};
$scope.dayClick = function(date) {
$scope.msg = "You clicked " + $filter("date")(date, "MMM d, y h:mm:ss a Z");
};
$scope.setContentViaService = function() {
var today = new Date();
MaterialCalendarData.setDayContent(today, '<span> :oD </span>')
}
$scope.getItems = function(){
if(localStorage.getItem("eventsData")){
var eventsData = localStorage.getItem("eventsData");
return JSON.parse(eventsData);
}else{
return [];
}
}
var events = $scope.getItems();
// You would inject any HTML you wanted for
// that particular date here.
var numFmt = function(num) {
num = num.toString();
if (num.length < 2) {
num = "0" + num;
}
return num;
};
var loadContentAsync = false;
$log.info("setDayContent.async", loadContentAsync);
$scope.setDayContent = function(date) {
var key = [date.getFullYear(), numFmt(date.getMonth()+1), numFmt(date.getDate())].join("-");
var data = (events[key]||[{ type: ""}]);
if (loadContentAsync) {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve(data);
});
return deferred.promise;
}
return data;
};
$scope.isAnimated = $stateParams.isAnimated;
});
Thank You Very Much for your time and help!!
Hi Use $ionicLoading Service to solve this problem,
http://ionicframework.com/docs/api/service/$ionicLoading/

ng-infinite scroll angular setting offset

Need to keep track of my offset so that I can get the next set each time either scroll or click 'Load more'. It improves performance. I am trying out here by setting offset and limit and passing as request params to my node server,but how to update or increment after that limit using offset:
my url as: /foo?limit=7&&offset=0;
My angular controller function as:
$scope.findDetails = function(){
var limit = 10;
var offset = 0;
//DataService.getUsers(limit,offset).then(function(customerdetails){
DataService.getUsers({limit,offset},function(customerdetails){
$scope.customers = customerdetails;
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
};
You must keep the offset in the scope of the controller and update the offset every time the infinite directive request more records to display:
$scope.limit = 10;
$scope.offset = 0;
//bind this function to the ng-infinite directive
$scope.infiniteScrollFunction = function() {
$scope.offset += $scope.limit;
$scope.findDetails();
};
$scope.findDetails = function() {
DataService.getUsers({limit: $scope.limit,offset: $scope.offset},
function(customerdetails){
...
}
var $scope.height = $('#div-height').height()
var flag = false;
var $scope.customers = []
$(window).scroll(function() {
if ($(this).scrollTop() > $scope.height-2000) {
if (!flag) {
flag = true;
refreshCustomers();
}
}
});
function refreshCustomers() {
DataService.getCustomers().then(function (data) {
$scope.customers = $scope.customers.concat(data);
setTimeout(function () {
$scope.height = $('#div-height').height();
flag = false
}, 0.1);
});
}
In DataService
factory.getCustomers = function(){
return $http.get(...api......&&limit=7).then(function (results) {
var customers = results.data.customers;
return customers;
});
};
Now after the window is scrolled up to certain height(windowHeight-2000px), the api is called again to get data. The previous data is being concatenated with present data.

Uploading images to Firebase with AngularJS

I have a service that handles "episodes": creating, deleting and updating them. It looks like this:
app.service('Episode', ['$firebase', 'FIREBASE_URL', function($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var episodes = $firebase(ref);
return {
all: episodes,
create: function(episode) {
location.reload();
//Add to firebase db
return episodes.$add(episode);
},
delete: function(episodeId) {
location.reload();
return episodes.$remove(episodeId);
},
update: function(episode) {
location.reload();
return episodes.$save(episode);
}
};
}]);
Inside my controller:
app.controller('AdminCtrl', ['$scope', 'Episode', function ($scope, Episode) {
$scope.episodes = Episode.all;
$scope.createEpisode = function(){
Episode.create($scope.episode).then(function(data){
$scope.episode.name = '';
$scope.episode.title = '';
$scope.episode.description = '';
$scope.episode.time = '';
$scope.episode.img = '';
});
};
$scope.deleteEpisode = function(episodeId){
if(confirm('Are you sure you want to delete this episode?') === true) {
Episode.delete(episodeId).then(function(data){
console.log('Episode successfully deleted!');
});
}
};
$scope.updateEpisode = function(episode) {
Episode.update($scope.episode).then(function(data) {
console.log('Episode successfully updated.');
});
};
The only example of uploading images to Firebase from AngularJS I've seen online is this: https://github.com/firebase/firepano
How am I able to incorporate this into an object based addition/update instead of finding it's index/link?

Resources