Loading Image from JSON file - ionic-framework

I'm trying to load an image from a JSON file into my ionic application.
I can load messages/strings from the JSON file but can't get images to work.
I've created a codepen:
http://codepen.io/beefman/pen/aOpKgL?embed-id=15603
HTML:
<img class="full-image" ng-src="{{item.source}}">
Javscript:
.controller('announcementCtrl', function($scope, $http) {
$scope.data = [];
$scope.infiniteLimit = 1;
$scope.doRefresh = function() {
$http.get('')
.success(function(data) {
$scope.data = data;
$scope.$broadcast('scroll.refreshComplete');
})
.error(function() {
$scope.data = [];
$scope.$broadcast('scroll.refreshComplete');
});
}

Try ng-src=... instead of src=... in the image tag since it's an angular directive.

Related

html2canvas screenshot size controle

I use this code from taking a screenshot & save it to pdf, I want to control the screenshot size like 400x700px.
<script type="text/javascript">
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG',20,20);
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}
</script>
Add height and width attribute to get you desired outcome :
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
canvas.setAttribute('width',400); /*this->add*/
canvas.setAttribute('height',700); /*this->add*/
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG');
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}

populate select with datajson using React js

I'm trying to populate a select using React js, I'm using the example given on the react js docs(https://facebook.github.io/react/tips/initial-ajax.html) , which uses jquery to manage the ajax calling, I'm not able to make it work, so far i have this:
here the codepen : http://codepen.io/parlop/pen/jrXOWB
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = result[''];
for (var k = 0; k < ten.length; k++) {
arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>);
}
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
html
<div id="root"></div>
any idea how to make it works, thanks.
You need to call setState to actually update your view. Here's a workable version.
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = [];
for (var k = 0; k < result.length; k++) {
arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
}
this.setState({
opts: arrTen
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);

How to show a picture stored as an pouchDB attachment using Angular in Ionic app

I'm making a mobile app using Ionic and pouchDB. In the DB I keep users data with their photos stored as attachments.
I want to make a list with users photos and names.
With getting names I have no problem but I can't figure out how to show the users photo in the list.
Records in the database look like this:
{
"_id": "1458320559128",
"_rev": "2-cc9bc75fffa165497a5448e63d7bc21f",
"firstName": "John",
"familyName": "Doe",
"gender": "male",
"email": "sgasd#dfdfvg.ds",
"phone": "423156523",
"address": "blah",
"country": "Venezuela",
"city": "Whatever",
"_attachments": {
"johndoe947.jpg": {
"content_type": "image/jpeg",
"revpos": 2,
"digest": "md5-Cw5m/SPn/cwtIguKKTcJDg==",
"length": 24296,
"stub": true
}
}
}
To show the list I use this view:
<ion-view view-title="Admin Area">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="customer in customers" type="item-text-wrap" href="#/tab/customers/{{ customer.id }}">
<img ng-src="{{customer.photo}}">
<h2>{{customer.firstName}} {{customer.familyName}}</h2>
<i class="icon ion-chevron-right icon-accessory"></i>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
And I retrieve the date using this controller:
.controller('MyCtrl', function($scope, PouchDB) {
$scope.customer = {};
$scope.customers = [];
var attachments;
localDB.allDocs({
include_docs: true,
attachments: true
}).then(function(result) {
for (var i = 0; i < result.rows.length; i++) {
attachments = result.rows[i].doc._attachments;
if (typeof attachments === 'undefined') { //if there is no attachment I put standard avatar. And this actually works OK.
var attch = "/img/nobody.jpg";
} else {
for (photoFileName in attachments) { break; } //so I take the first attachment if there was more...
//this part is a mistery (and of course doesn't work) - how can I get attachment from the DB and directly show it on the page?
attch = localDB.getAttachment(result.rows[i].doc.id, photoFileName)
.then(function (blob) {
var url = URL.createObjectURL(blob);
var img = document.createElement('img');
img.src = url;
return img;
}).catch(function (err) {
console.log(err);
});
}
var obj = {
"id": result.rows[i].doc._id,
"firstName": result.rows[i].doc.firstName,
"familyName": result.rows[i].doc.familyName,
"attch": attch
}
$scope.customers.push(obj);
$scope.$apply();
}
}).catch(function(err) {
console.log(err);
});
I was reading PouchDB documentation many times and using their examples I made something working to some extend. But it's not what I want:
$scope.showPic = function(id) {
localDB.get(id, {attachments: true}).then(function(doc) {
attachments = doc._attachments;
for (photo in attachments) { break; }
}).then(function() {
return localDB.getAttachment(id, photo);
}).then(function (blob) {
var url = URL.createObjectURL(blob);
var img = document.createElement('img');
img.src = url;
var elem = document.getElementById(elemid);
elem.appendChild(img);
}).catch(function (err) {
console.log(err);
});
}
Using this above I can actually put a photo into some element with ID elemid when I call the function in the view like this: {{ showPic(id) }}
But I don't think it's a good way to do it.
I'd say this is more of an Angular question than a PouchDB question, but I'll try to answer.
Basically PouchDB is giving you a method that asynchronously provides a URL to an image:
doStuff().then(function (blob) {
var url = URL.createObjectURL(blob);
// now I have a url
});
I.e. this is the same thing that would happen if your remote server was giving you a URL somehow (e.g. via $http). I find it helps to think of PouchDB as a remote server, since it's asynchronous.
Now, instead of attaching the image URL directly to the <img> tag, you can attach it to your scope and then update the scope:
myScope.imgTag = url;
$rootScope.$apply();
Then you just have an HTML block like:
<img src="myScope.imgTag"/>
Note that if you wrap PouchDB's promises in $q.when(), then the $rootScope.$apply() is done automatically for you. Good luck!
I'm using ionic 1.3 pouchDB syncing with couchDB but unable to display images see example here:.
Controller:
$pouchDB.getAttachmentById('main','bares.jpg').then(function(response) {
var url = URL.createObjectURL(response);
$scope.imgTag = url;
console.log("attachments teste:")
//console.log(response);
console.log($scope.imgTag);
});
Service:
this.getAttachmentById = function(docId, attName) {
var deferred = $q.defer();
console.log("getAttachmentById: " + docId+" " + attName)
database.getAttachment(docId,attName).then(function(response) {
deferred.resolve(response);
console.log("/************ ");
console.log(response);
console.log("**************/");
}).catch(function(error) {
deferred.reject(error);
});
return deferred.promise;
}
View:
html
img src="scope.imgTag"
console.log:
attachments teste: controllers.js:60
blob:http://localhost:8101/a37abb3d-60b1-45a6-9c7c-6516a7c83fce

[Ionic][Onesignal] How to refresh page when notification clicked

I want my app automatically refresh to retrieve latest data from API whenever user press the notification sent by onesignal pushnotification server. Below is my sample code, I having trouble to call controller function to dorefresh() from App.js. Or is there any other workaround can let me retrieve latest data?
App.js
angular.module('starter', ['ionic','starter.controllers'])
.run(function($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function() {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
$ionicHistory.clearCache();
$window.location.reload(true);
};
// Update with your OneSignal AppId and googleProjectNumber before running.
window.plugins.OneSignal.init("xxxxxxxxxxxxxxxx",
{googleProjectNumber: "xxxxxxxxxxxxxx"},
notificationOpenedCallback);
});
})
Controller.js
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$http.get("localhost/test/getitem.php")
.success(function (response)
{
$scope.items = response;
});
$scope.doRefresh = function() {
console.log("Refreshing!");
$http.get("localhost/test/getitem.php")
.success(function(response) {
$scope.items = formatData(response);
})
.finally(function() {
$scope.$broadcast('scroll.refreshComplete')
})
};
Index.html
<ion-refresher pulling-text="Pull to refresh" on-refresh="doRefresh()">
</ion-refresher>
<div class="item">
<h2 style="text-align:center; font-size:25px; font-weight:">{{item.name}}</h2>
</div>
You can broadcast an event in the notificationOpenedCallback:
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
// $ionicHistory.clearCache();
// $window.location.reload(true);
$rootScope.$broadcast('app:notification', {refresh: true});
};
As you can see I've created a custom event app:notification and used the $rootScope to broadcast it ($broadcast) to the children scopes.
I've attached an object with some info your receiver can use.
Now in your controller you can intercept the event using $scope.$on and call your refresh function:
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$scope.$on('app:notification', function(event, data) {
console.log(data);
if (data.refresh)
{
$scope.doRefresh();
}
});
});
NOTES:
You don't really need to clean the cache here $ionicHistory.clearCache();.

bootstrap typeahead url/redirect

$(function(){
var orthoObjs = {};
var orthoNames = [];
var throttledRequest = _.debounce(function(query, process){
$.ajax({
url: 'json/ortho4.json'
,cache: false
,success: function(data){
orthoObjs = {};
orthoNames = [];
_.each( data, function(item, ix, list){
orthoNames.push( item.searchPhr );
orthoObjs[ item.searchPhr ] = item;
});
process( orthoNames );
}
});
}, 300);
$(".typeahead").typeahead({
source: function ( query, process ) {
throttledRequest( query, process );
}
,updater: function (item) {
var url = "orthoObjs[item.searchUrl]";
window.location = url;
Whats the best way to get the redirect to work? I have seen similar questions, but can't get this to work. Documentation on typeahead isn't great. I am using underscore.js for the each function. Just want a simple search query that redirects when the user selects.
I actually got this to work. I got a little help... but here it is. There is the JSON file..
[
{ "id":1, "searchUrl":"invisalign.html", "name":"invisalign" }
,{ "id":2, "searchUrl":"invisalign.html", "name":"invisalign teen" }
,{ "id":3, "searchUrl":"clearbraces.html", "name":"clear braces" }
]
And the HTML code....
Lots of good stuff here.. http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead
And the search code..
<form method="post" id="myForm" class="navbar-search pull-left">
<input
type="text"
class="search-query typeahead"
placeholder="Search Our Website"
autocomplete="off"
data-provide="typeahead"
/>
<i class="fa-icon-search icon-black"></i>
</form> </li>
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: '/json/bonds.json'
,cache: false
,success: function(data){
bondObjs = {};
bondNames = [];
_.each( data, function(item, ix, list){
bondNames.push( item.name );
bondObjs[ item.name ] = item.searchUrl;
});
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
window.location.href =bondObjs[ selectedName ];
}
});
});
</script>