JSON won't save on scope AngularJS - 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);
});

Related

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.

No output with ng-repeat

i have a problem with this ng-repeat statement.
<div ng-repeat="m in mbct.messages track by $index" ng-click="mbct.message_click($index)" ng-class="mbct.set_class(m.gelesen)">
<div>ABS: <span ng-bind="m.abs"></span> </div>
<div>Betreff: <span ng-bind="m.betreff"></span> </div>
<div>Wann: <span ng-bind="m.timestamp"></span> </div>
<hr>
</div>
Controller:
var self = this;
self.messages = [];
self.massages_length = "";
//initialize variables when app starts
self.init = function(){
alert("Init-runs");
MessageService.get_messanges().then(
function(response){
self.messages = response.data;
self.messages_length = self.messages.length;
console.log(self.messages_length);
}
)
};
self.get_message_loop = $interval(function(){
MessageService.get_messanges().then(
function(response) {
if(self.messages_length < response.data.length){
console.log("new message");
self.messages = response.data;
self.messages_length = self.messages.length;
console.log("self.messages_length:" + self.messages_length);
}
else{
console.log("no new message");
}
}
);
},500);
And my Service:
gsgmain.factory('MessageService',['$http',function($http){
return{
get_messanges : function(){
var email = $("#php_username").html();
var data = {user_email: email, methode: "get_all_msg"};
var json_data = angular.toJson(data);
return $http.post("php/server.php", json_data);
},
send_message : function(abs,emp,message_text,betreff){
var data = {abs:abs, emp: emp, message: message_text,betreff:betreff,methode:"send_message"};
var json_data = angular.toJson(data);
return $http.post("php/server.php",json_data);
},
set_read: function(msg_id){
var data = {msg_id: msg_id,methode: "set_read"};
var json_data = angular.toJson(data);
return $http.post("php/server.php",json_data);
}
}
}]);
The ng-repeat-statement has no output, since i added the if-else-statement in "get_message_loop" to check if there are new messages.
Before the get_message_loop function looked like this:
self.get_message_loop = $interval(function(){
MessageService.get_messanges().then(
function(response) {
self.messages = response.data;
}
);
},500);
and erverything works fine.
Could you tell me why?
Thank you in advance.
me again :D,
I solved the Problem. I defined the controller twice. One time in the html-tag and the other time in my routeprovider. So the code did everything twice.
And always in the second run, the variable self.messages_length was undefined.
I removed one definition and now everything works fine ;)

Two $firebaseArrays on one page & one ctrl

I would like to use two different $firebaseArrays on one view with one controller. But only one of them works and the other only works if i put him in his own controller.
from my factory file:
.factory("AlphaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('alpha/');
return $firebaseArray(ref);
}
])
.factory("BetaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('beta/');
return $firebaseArray(ref);
}
])
and my controller:
.controller('DemoCtrl', function($scope, AlphaFactory, BetaFactory) {
$scope.alphaJobs = AlphaFactory;
$scope.addalphaJob = function() {
$scope.alphaJobs.$add({
Testentry: $scope.loremipsum,
timestamp: Date()
});
$scope.alphaJob = "";
};
$scope.betaJobs = BetaFactory;
$scope.addbetaJob = function() {
$scope.betaJobs.$add({
Testentry2: $scope.dolorest,
timestamp: Date()
});
$scope.betaJob = "";
};
)}
Are you sure it is not a simple matter of a promise has not finished?
var alphaJobs = AlphaFactory;
alphaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.alphaJobs = alphaJobs;
});
var betaJobs = BetaFactory;
betaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.betaJobs = betaJobs;
});

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.

Ionic Infinite Scroll with http.post results

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.

Resources