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>
Related
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 ;)
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;
});
Basically I have a timeline with posts that is a $firebaseArray and any change to this array is getting binded properly. But when I want to bind any other data it only binds when ngInfiniteScroll is trying to retrieve more data from firebase, so only when I scroll down.
In the code bellow I'm calling {{getMoreDetails()}} and this data is binded when the first set of data is being retrieved with ngInfiniteScroll but as soon as it is loaded the bind breaks and only binds again when scrolling.
My concerns here are:
Was ngInfiniteScroll designed to work this way?
Is there any workaround in this scenario?
Stack:
"firebase": "2.4.2","angularfire": "~1.2.0","firebase-util": "0.2.5","ngInfiniteScroll": "1.2.2"
timeline.html
<div ng-controller="TimelineController">
<section class="entrys main-content" infinite-scroll="posts.scroll.next(3)" infinite-scroll-distance="0.3">
<div class="inner">
<div ng-repeat="post in filteredPostsResults = (posts | filter:postIdFilter)">
<article class="entry">
<img ng-if="post.sourceType=='IMAGE'" data-ng-src="{{getPostData(post)}}"/>
<div class="entry-info">
<h3><div ng-bind-html="post.description | emoticons"></div></h3>
<small>posted on <time>{{getDateInFormat(post.createdAt)}}</time></small>
{{getMoreDetails()}}
</div>
</article>
</div>
</div>
</section>
</div>
timeline.js
(function (angular) {
"use strict";
var timeline = angular.module('myApp.user.timeline', ['firebase', 'firebase.utils', 'firebase.auth', 'ngRoute', 'myApp.user.timelineService']);
timeline.controller('TimelineController', [ '$scope', '$routeParams', 'TimelineService', '$publisherServices', '$securityProperties', function ($scope, $routeParams, TimelineService, $publisherServices, $securityProperties) {
if (!$scope.posts){
$scope.posts = TimelineService.getPosts($routeParams.userId);
}
$scope.posts.$loaded(function(result) {
$scope.isPostsLoaded = true;
});
$scope.getMoreDetails = function() {
console.log("LOGGED ONLY WHEN SCROLLING");
return $publisherServices.getDetails();
};
$scope.getPostData = function(post) {
if (!post.dataUrl){
post.dataUrl = $publisherServices.getAwsFileUrl(post.fileName);
}
return post.dataUrl;
};
$scope.postIdFilter = function(post) {
if ($routeParams.postId){
if (post.$id == $routeParams.postId) return post;
} else { return post; }
};
$scope.getDateInFormat = function(timestamp){
var date = new Date();
date.setTime(timestamp);
return date;
};
}]);
})(angular);
timelineService.js
(function (angular) {
"use strict";
var timelineService = angular.module('myApp.user.timelineService', []);
timelineService.service('TimelineService', ['$routeParams', 'FBURL', '$firebaseArray', function ($routeParams, FBURL, $firebaseArray) {
var posts;
var currentUserIdPosts;
var postsRef;
var self = {
getPosts: function(userId){
if (!posts || userId != currentUserIdPosts){
currentUserIdPosts = userId;
postsRef = new Firebase(FBURL).child("posts").child(userId);
var scrollRef = new Firebase.util.Scroll(postsRef, "createdAtDesc");
posts = $firebaseArray(scrollRef);
posts.scroll = scrollRef.scroll;
}
return posts;
}
}
return self;
}]);
})(angular);
I am assuming that you want the post details updated when the data from your Firebase changes.
When Firebase changes are applied to your scope, it seems that it doesn't trigger a digest cycle, so you probably need to do it manually every time you get updates from Firebase.
Take a look at $$updated in $firebaseArray.$extend (see docs).
// now let's create a synchronized array factory that uses our Widget
app.factory("WidgetFactory", function($firebaseArray, Widget) {
return $firebaseArray.$extend({
// override the update behavior to call Widget.update()
$$updated: function(snap) {
// we need to return true/false here or $watch listeners will not get triggered
// luckily, our Widget.prototype.update() method already returns a boolean if
// anything has changed
return this.$getRecord(snap.key()).update(snap);
}
});
});
I hope this helps.
Sorry for a very stupid question but I just started working with AngularJS and OnsenUI.
I have got a service to get a data from SQLite:
module.factory('$update', function () {
var update = {};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM event_updates', [], function (tx, results) {
var rows = results.rows;
update.items = [];
if (!rows.length) {} else {
for (var index = 0; index < rows.length; index++) {
update.items.push({
"title": rows.item(index).title,
"date": rows.item(index).date,
"desc": rows.item(index).desc
});
}
}
}, function (error) {
console.log(error);
});
});
return update;
});
And a controller which is using the data:
module.controller('UpdatesController', function ($scope, $update) {
$scope.items = $update.items;
});
As soon as my page is loaded the content is not displayed and I need to click twice to call a page with the code below to see the content:
<ons-list ng-controller="UpdatesController">
<ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in items" ng-click="showUpdate($index)">
<div class="list-item-left">
</div>
<div class="list-item-right">
<div class="list-item-content">
<div class="name">{{item.title}}</div> <span class="desc">{{item.desc}}</span>
</div>
</div>
</ons-list-item>
</ons-list>
Can anybody help how can I initialise the controller as soon as page is loaded with all content. Sorry if it is a stupid question but I am really struggling. Appreciate your help a lot.
You could store the result of the request in the factory and retrieve those instead.
module.factory('$update', function () {
var update = {};
var requestValues = function(){ // store the results of the request in 'update'
// Your db.transaction function here
}
var getUpdates = function(){ // retrieve the values from 'update'
return update;
}
return{
requestValues : requestValues,
getUpdates : getUpdates
}
});
And then in you controller:
module.controller('UpdatesController', function ($scope, $update) {
$update.requestValues();
$scope.items = $update.getUpdates();
});
You could then get the values from anywhere in you solution (by using $update.getUpdates) without having to make an extra http request.
I'm currently learning angular and have hit a roadblock.
The second factory (shown below) makes an http request like this: http://example.com/api/get_post/?post_id=7129&callback=JSON_CALLBACK');
I want the post ID to be a variable. So depending on which blog title is clicked, I can pass the correct variable into that http request.
In other words, I guess I want to take a result from the first factory (blogAPIservice) and use it in the second factory.
Makes sense??
<!-- FACTORIES -->
angular.module('blogApp.services',[])
.factory('blogAPIservice',function($http) {
var blogAPI = [];
var blogs = $http.jsonp('http://example.com/api/get_recent_posts/?count=10&callback=JSON_CALLBACK');
blogs.success(function(data) {
$.each(data.posts, function(i, blog) {
var fromNow = moment(blog.date).fromNow();
blogAPI.push({
url: blog.url,
title: blog.title,
excerpt: blog.excerpt,
date : fromNow,
id: blog.id
})
});
});
var factory = {};
factory.getBlogs = function () {
return blogAPI;
};
return factory;
})
.factory('singlePostService',function($http) {
var singleAPI = [];
var postID = '7129';
var singlePost = $http.jsonp('http://example.com/api/get_post/?post_id=7129&callback=JSON_CALLBACK');
singlePost.success(function(data) {
singleAPI.push({
title: data.post.title,
content: data.post.content
})
});
var factory = {};
factory.getSinglePost = function () {
return singleAPI;
};
return factory;
})
And here are the controllers:
angular.module('blogApp.controllers', [])
.controller('resultsController',function($scope, blogAPIservice) {
$scope.keywordFilter = null;
$scope.blogs = [];
init();
function init() {
$scope.blogs = blogAPIservice.getBlogs();
}
function grabID() {
$(this).attr('rel');
}
})
.controller('singlePostController',function($scope, singlePostService) {
$scope.keywordFilter = null;
$scope.singlePost = [];
init();
function init() {
$scope.singlePost = singlePostService.getSinglePost();
}
})
And finally the markup:
<li ng-repeat="blog in blogs">
{{ blog.title }}
</li>
You can inject the first service into the second one like this:
.factory('singlePostService',function($http, blogAPIservice) {
//Do something with blogAPIservice
}
For more information about depenency injection read the docs