No output with ng-repeat - angularjs

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 ;)

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);
});

Get a list of contacts using cordova?

Sorry for my bad English.
How to get a list of contacts by using the Cordova angularjs?
Thanks in advance. Kind regards.
I don't know how your cordova-app is built up and but you could do it this way( take into consideration that I've not tested this):
Code:
First request contacts of your device by using the condact-plugin of cordova:
(same link as provided earlier: http://docs.phonegap.com/en/edge/cordova_contacts_contacts.md.html)
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// when using the plugin:
// you can put it within your angularjs-controllers
// where it will be executed and onSuccess-callback is called.
var options = new ContactFindOptions();
options.filter = "";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// within this function you have to assign contacts to a model
function onSuccess(contacts) {
$scope.contacts = contacts;
}
function onError(contactError) {
alert('onError!');
}
HTML:
Iterate over each contact-object of your contacts-collection assigned within onSuccess-function:
<div ng-repeat="contact in contacts">{{contact.name.formatted}}</div>
Tutorial: http://www.quora.com/What-is-the-way-to-get-all-contacts-using-PhoneGap-on-Android
Putting the plugin into a angularjs-controller could look like this:
angular.module('aModule', [])
.controller('contactCtrl', ['$scope', function($scope) {
var options = new ContactFindOptions();
options.multiple = true;
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields,
function(contacts){
var arr = [];
for (var i = 0; i < contacts.length; i++)
{
arr.push({name: contacts[i].name.formatted})
}
$scope.contacts = arr;
},
function(error){ console.log(error); },
options
);
}])
HTML:
<div ng-app="aModule" ng-controller="contactCtrl">
<div ng-repeat="contact in contacts">{{contact.name}}</div>
</div>

How to use Parse JS SDK in Angular.js service?

I'll explain my problem with a quick example.
Parse.initialize("nlxy5xYYZQ1fLfFkzcyLHOifkie1dOU0ZSxoxw1w", "IRBJO7nyd1vQquhMvnyMd298ZVJ0qWg1AjxBY5nr");
var People = Parse.Object.extend("People");
var app = angular.module('app', []);
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
$scope.people = PeopleService.getPeople();
}]);
app.service("PeopleService", function(){
var people = null;
return {
getPeople: function(){
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
return people;
},
error: function (error) {
console.error("Error: " + error.code + " " + error.message);
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<script src="https://www.parsecdn.com/js/parse-1.3.2.min.js"></script>
<div ng-app="app">
<ul ng-controller="MyCtrl">
<li ng-repeat="person in people">{{person}}</li>
</ul>
</div>
Now, of course, the scope in the controller doesn't update when the data is returned by Parse.
How can I make this service work properly?
As #james stated before, using promises in $q service is what you are looking for. Here's how it could go with your example.
getPeople: function(){
var deferred = $q.defer();
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
deferred.resolve(people);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
This returns a promise which you can use like this
$scope.people = PeopleService.getPeople();
or
$scope.people = PeopleService.getPeople()
.then(function(people) {
//modify data as necessary
return people
}, function(reason) {
alert('Failed: ' + reason);
}
);

How can I use the exact same array from one service in two controllers?

I have this code:
controller:
function deleteRootCategory(){
$scope.rootCategories[0] = '';
}
function getCategories(){
categoryService.getCategories().then(function(data){
$scope.rootCategories = data[0];
$scope.subCategories = data[1];
$scope.titles = data[2];
});
}
getCategories();
service:
var getCategories = function(){
var deferred = $q.defer();
$http({
method:"GET",
url:"wikiArticles/categories"
}).then(function(result){
deferred.resolve(result);
});
}
return deferred.promise;
}
html:
<div ng-controller="controller">
<div ng-repeat="root in rootCategories"> {{root}} </div>
<div ng-repeat="sub in subCategories"> {{sub}} </div>
<div ng-repeat="title in titles">{{title}}</div>
</div>
html2:
<div ng-controller="controller">
<div ng-include src="html"></div>
<button ng-click="deleteRootCategory()">Del</button>
</div>
When I click the deleteRootCategory-button the array $scope.rootCategories is updated, but the view won't ever change.
What am I missing?
Thanks
You will probably want to have a broadcast event set up when the value is changed in the service. Something like this.
.service("Data", function($http, $rootScope) {
var this_ = this,
data;
$http.get('wikiArticles/categories', function(response) {
this_.set(response.data);
}
this.get = function() {
return data;
}
this.set = function(data_) {
data = data_;
$rootScope.$broadcast('event:data-change');
}
});
Have both controllers waiting for the event, and using the set to make any changes to the array.
$rootScope.$on('event:data-change', function() {
$scope.data = Data.get();
}
$scope.update = function(d) {
Data.set(d);
}

Angular call service on asynchronous data

I have a service that make some calls to retrieve data to use in my app. After I've loaded data, I need to call another service to make some operations on my data. The problem is that second service will not have access to the data of the first service.
I've made a plunker: plunkr
First service
app.factory('Report', ['$http', function($http,$q){
var Authors = {
reports : [],
requests :[{'url':'data.json','response':'first'},
{'url':'data2.json','response':'second'},
{'url':'data3.json','response':'third'}]
};
Authors.getReport = function(target, source, response, callback) {
return $http({ url:source,
method:"GET",
//params:{url : target}
}).success(function(result) {
angular.extend(Authors.reports, result)
callback(result)
}
).error(function(error){
})
}
Authors.startQueue = function (target,callback) {
var promises = [];
this.requests.forEach(function (obj, i) {
console.log(obj.url)
promises.push(Authors.getReport(target, obj.url, obj.response, function(response,reports){
callback(obj.response,Authors.reports)
}));
});
}
return Authors;
}])
Second service
app.service('keyService', function(){
this.analyze = function(value) {
console.log(value)
return value.length
}
});
Conroller
In the controller I try something like:
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports,keyService) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
});
$scope.test = function(value){
keyService.analyze($scope.report.about);
}
I think this is what you are going for? Essentially, you want to call the second service after the first succeeds. There are other ways of doing this, but based on your example this is the simplest.
http://plnkr.co/edit/J2fGXR?p=preview
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
$scope.test($scope.report.about); //added this line
});
$scope.test = function(value){
$scope.example = keyService.analyze(value); //changed this line to assign property "example"
}
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p>Progress notification : {{progress}}!</p>
<div ng-show="show">
<progress percent="progressBar" class="progress-striped active"></progress>
</div>
<pre>{{report}}</pre>
<pre>{{report.about}}</pre>
{{example}} <!-- changed this binding -->
</body>

Resources