how to uplaod multiple images from i pad gallery using ionic and cordova plugin? - angularjs

I want to upload multiple images in iPad using ionic and cordovaImagePicker plugin.
I am getting an error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module ngCordova due to:
Error: [$injector:nomod] Module 'ngCordova' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I am not getting how to exactly use that plugin + how to test whether its working or not?
app.js:
var app = angular.module('starter', ['ionic','ngCordova']);
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
});
app.controller('ImagePickerController', function($scope, $cordovaImagePicker, $ionicPlatform, $cordovaContacts) {
$scope.collection = {
selectedImage : ''
};
$ionicPlatform.ready(function() {
$scope.getImageSaveContact = function() {
// Image picker will load images according to these settings
var options = {
maximumImagesCount: 1, // Max number of selected images, I'm using only one for this example
width: 800,
height: 800,
quality: 80 // Higher is better
};
$cordovaImagePicker.getPictures(options).then(function (results) {
// Loop through acquired images
for (var i = 0; i < results.length; i++) {
$scope.collection.selectedImage = results[i]; // We loading only one image so we can use it like this
window.plugins.Base64.encodeFile($scope.collection.selectedImage, function(base64){ // Encode URI to Base64 needed for contacts plugin
$scope.collection.selectedImage = base64;
$scope.addContact(); // Save contact
});
}
}, function(error) {
console.log('Error: ' + JSON.stringify(error)); // In case of error
});
};
});
Here is my code on plunker.

my app.js file.
var app = angular.module('starter', ['ionic','ngCordova']);
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
});
app.controller('ImagePickerController', function($scope, $cordovaImagePicker, $ionicPlatform, $cordovaContacts) {
$scope.collection = {
selectedImage : ''
};
$ionicPlatform.ready(function() {
alert("hiii");
$scope.getImageSaveContact = function() {
// Image picker will load images according to these settings
var options = {
maximumImagesCount: 1, // Max number of selected images, I'm using only one for this example
width: 800,
height: 800,
quality: 80 // Higher is better
};
$cordovaImagePicker.getPictures(options).then(function (results) {
// Loop through acquired images
for (var i = 0; i < results.length; i++) {
$scope.collection.selectedImage = results[i]; // We loading only one image so we can use it like this
window.plugins.Base64.encodeFile($scope.collection.selectedImage, function(base64){ // Encode URI to Base64 needed for contacts plugin
$scope.collection.selectedImage = base64;
$scope.addContact(); // Save contact
});
}
}, function(error) {
console.log('Error: ' + JSON.stringify(error)); // In case of error
});
};
});
$scope.contact = { // We will use it to save a contact
"displayName": "Gajotres",
"name": {
"givenName" : "Dragannn",
"familyName" : "Gaiccc",
"formatted" : "Dragannn Gaiccc"
},
"nickname": 'Gajotres',
"phoneNumbers": [
{
"value": "+385959052082",
"type": "mobile"
},
{
"value": "+385914600731",
"type": "phone"
}
],
"emails": [
{
"value": "dragan.gaic#gmail.com",
"type": "home"
}
],
"addresses": [
{
// "type": "home",
"formatted": "Some Address",
"streetAddress": "Some Address",
"locality":"Zagreb",
"region":"Zagreb",
"postalCode":"10000",
"country":"Croatia"
}
],
"ims": null,
"organizations": [
{
"type": "Company",
"name": "Generali",
"department": "IT",
"title":"Senior Java Developer"
}
],
"birthday": Date("08/01/1980"),
"note": "",
"photos": [
{
"type": "base64",
"value": $scope.collection.selectedImage
}
],
"categories": null,
"urls": null
}
$scope.addContact = function() {
$cordovaContacts.save($scope.contact).then(function(result) {
console.log('Contact Saved!');
}, function(err) {
console.log('An error has occured while saving contact data!');
});
};
});
run the code inside x code otherwise it will always show the error cordova is not defined.

Related

Adding a Clickable Dot to a World Map Using JQuery VMap

I've recently inherited a project which is using jqvmap.
There's a map of the world with a column of clickable dots on it:
Whilst I have been able to find the code which seems to add those dots, I cannot figure out how this data was generated:
jQuery.fn.vectorMap('addMap', 'world_en', {
"width": 950, "height": 550, "paths": {
"id": { "path": "M781.68,324.4l-2.31,8.68l-12.53,4.", ... ... ... "name": "Pakistan" },
"in": { "path": "M670.98,313.01l4.58-2.24l2.72-9,"... ... ... "name": "India" },
"np": { "path": "M671.19,242.56l0.46,4.2, ... ... ... "name": "Greece" },
"demo": {
"path": "M922.59,148a8.59,8.59,0,1,1-8.59-8.59C918.76,139,922.59,143.27,922.59,148Z",
"name": "Demo"
},
"Demo2": {
"path": "M922.59,80A8.59,8.59,0,1,1,914,71.42C918.76,71,922.59,75.27,922.59,80Z",
"name": "Demo2"
},
"Demo3": {
"path": "M922.59,114a8.59,8.59,0,1,1-8.59-8.59C918.76,105,922.59,109.27,922.59,114Z",
"name": "Demo3"
},
"Demo4": {
"path": "M922.59,182a8.59,8.59,0,1,1-8.59-8.59C918.76,173,922.59,177.27,922.59,182Z",
"name": "Demo4"
},
"Demo5": {
"path": "M922.59,216a8.59,8.59,0,1,1-8.59-8.59C918.76,207,922.59,211.27,922.59,216Z",
"name": "Demo5"
}
}
});
I need to add another dot.
Is there a tool which the previous developer has used?
Is there a guide somewhere which explains how to go about doing such a thing.
I've searched Google and looked at the Github site for vmap and have not found anything which could explain this.
Here's the code in jquery's ready function which set's the map up:
$(document).ready(function () {
$("#hidCountrySU").val('');
$("#hidServerCode").val('');
$('#lblServerName').text(' Select server to test ');
$('#btnSubmitServer').attr('disabled', 'disabled');
// List of Regions we'll let clicks through for
let enabledRegions = ['demo', 'demo2', 'demo3', 'demo4', 'demo5'];
let map = null;
// Store currentRegion
let currentRegion = 'demo';
map = $('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#fff',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#F90606',
enableZoom: false,
showTooltip: true,
values: sample_data,
scaleColors: ['#C8EEFF', '#006491'],
colors: {
demo: '#F78774',
demo2: '#F78774',
demo3: '#F78774',
demo4: '#F78774',
demo5: '#F78774'
},
normalizeFunction: 'polynomial',
selectedRegions: ['aue'],
onRegionClick: function (event, code, region) {
// Check if this is an eabled region, and not the current selected on
if (enabledRegions.indexOf(code) === -1) {
// Not an enabled region
event.preventDefault();
} else {
// Enabled region. Update newly selected region.
currentRegion = code;
$('.selectedRegionColor').removeClass('selectedRegionColor');
$('#jqvmap1_' + code).addClass('selectedRegionColor');
}
},
onRegionSelect: function (event, code, region) {
localStorage.setItem("locationSelected", "true");
if (code == 'demo') {
$("#hidCountrySU").val('countryAU');
$("#hidServerCode").val('demo');
$('#lblServerName').text(' demo testing ');
$('#btnSubmitServer').removeAttr('disabled');
} else if (code == 'demo2') {
$("#hidCountrySU").val('countryAU');
$("#hidServerCode").val('demo2');
$('#lblServerName').text(' demo2 testing ');
$('#btnSubmitServer').removeAttr('disabled');
} else if (code == 'demo3') {
$("#hidCountrySU").val('countryAU');
$("#hidServerCode").val('Demo3');
$('#lblServerName').text(' Demo3 testing ');
$('#btnSubmitServer').removeAttr('disabled');
} else if (code == 'demo4') {
$("#hidCountrySU").val('countryAU');
$("#hidServerCode").val('demo4');
$('#lblServerName').text(' B Demo ');
$('#btnSubmitServer').removeAttr('disabled');
} else if (code == 'demo5') {
$("#hidCountrySU").val('countryAU');
$("#hidServerCode").val('demo5');
$('#lblServerName').text(' demo5 ');
$('#btnSubmitServer').removeAttr('disabled');
if ($("#form_ServerSubmitFromServer").length === 1) {
$("#form_ServerSubmitFromServer").submit();
}
else if ($("#form_ServerSubmitFormServer2").length === 1) {
$("#form_ServerSubmitFormServer2").submit();
}
},
onLabelShow: function (event, label, code) {
if (enabledRegions.indexOf(code) === -1) {
event.preventDefault();
}
}
});
});
Obviously the first snippet is extending the vectorMap.
I can only assume the previous dev used some kind of image editing program like Inkscape to add the dot and somehow get the path for it. But I just don't know.
Thanks

AngularJS: mocking the service in a controller using Jasmine

Could you please help me to write down the Jasmine(2.0) test code for mock of the service in a Controller as below.
readJsonFactory.js
angular.module('myAssignmentTaskApp')
.factory('readJsonFactory', function ($http) {
var userExists = false;
var responseData = [];
return $http.get('../json/AutoTestDB1.json').then(function (response) {
for (var i=0; i<response.data.StatusTable.length; i++){
responseData.push(response.data.StatusTable[i].RunId);
}
return response;
}).catch(function (error) {
//
})
});
The Controller file readjson.js is as below.
angular.module('myAssignmentTaskApp')
.controller('ReadjsonctrlCtrl', function ($scope,readJsonFactory,$location) {
var testCaseNameFromReadJsonFactory = [];
readJsonFactory.then(function (response) {
for (`var i=0;i<response.data.StatusTable.length;i++`){
testCaseNameFromReadJsonFactory.push(response.data.StatusTable[i].TestScenario);
}
}
})
AutoTestDB1.json
{
"StatusTable": [
{
"RunId": "bah_regression_alternateFlights",
"TestScenario": "BAH - Change Default Search Options",
"Area": "Yes",
"TestCases": [
{
"TestID": "",
"TestName": "VerifyCarDepotPageIsDisplayed_Test",
"Status": [
{
"Release": " R301",
"Runner": "yes",
"Status": "Passed",
"details": [
{
"ResponseTime": "1m 26s 702ms",
"Status": "Passed",
"RecordData": 1511519114413
}
]
}
]
}
]
}
]
}
Please post an apporopriate spac.js file.
Thanks in advance.
You do use the following to mock your service
beforeEach(function() {
angular.mock.module('myAssignmentTaskApp', ($provide) => {
const mockReadJsonFactory = {
};
$provide.constant('readJsonFactory', mockReadJsonFactory);
});
});

Unable to show JSON data injected using service inside the amchart directive dataprovider

I am using amcharts as a custom directive. Now I want to fetch the dataProvider of this AmChart from the output of the $http.get service using webservices.
But I am unable to get this dynamically assigned to the dataprovider of the amChart.
var app=angular.module('mainApp',[]);
app.service('dataProviderService',function($http){
this.getData= function(){
return $http.get('jaxrs/WebService/getJSONData');
};
});
app.directive('myChart',['dataProviderService',function (dataProviderService) {
return {
restrict: 'E',
replace:true,
template: '<div id="chartdiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>',
link: function (scope, element, attrs) {
scope.data={};
dataProviderService.getData().then(function(response){
scope.data=response.data;
},function(error){
scope.status="Show error";
});
var chart = false;
var initChart = function() {
if (chart) chart.destroy();
var config = scope.config || {};
chart = AmCharts.makeChart( "chartdiv", {
"theme": "none",
"type": "serial",
"dataProvider": dataProviderService.newData(),
"categoryField": "OT",
"depth3D": 20,
"angle": 30,
"categoryAxis": {
"labelRotation": 90,
"gridPosition": "start"
},
"valueAxes": [ {
"title": "availability"
} ],
"graphs": [ {
"valueField": "availability",
"colorField": "color",
"type": "column",
"lineAlpha": 0.1,
"fillAlphas": 1
} ],
"chartCursor": {
"cursorAlpha": 0,
"zoomable": false,
"categoryBalloonEnabled": false
},
"export": {
"enabled": true
}
} );
};
initChart();
}//end watch
}
}]) ;
Assuming your newData() method is an asynchronous $http.get() request like your getData() method, you need to either call makeChart after the request resolves itself or tell the chart to redraw itself by calling validateData() when the request resolves itself. Here's an example of doing this inside the chart's init event:
chart = AmCharts.makeChart( "chartdiv", {
// ... omitted ...
"dataProvider": [],
// ... omitted ...
"listeners": [{
"event": "init",
"method": function(e) {
dataProviderService.newData().then(function(response) {
e.chart.dataProvider = response;
e.chart.validateData();
}, function(error) {
// do something else
});
}
}]
} );

read data from pre populated database file in ionic

I am new to ionic framework. I am reading data from populated database file in ionic.the database file is in json format. In json file my database name, table name and data available. How to read data from this database file using angularjs in ionic
I followed this tutorial:https://www.thepolyglotdeveloper.com/2015/01/deploy-ionic-framework-app-pre-filled-sqlite-db/
var db;
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova'])
.run(function ($ionicPlatform, $cordovaSQLite) {`enter code here`
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
window.plugins.sqlDB.copy("gr.json", function() {
db = $cordovaSQLite.openDB("grocery.db");
}, function(error) {
console.error("There was an error copying the database: " + error);
db = $cordovaSQLite.openDB("grocery.db");
});
});
})
This is my controller.js
angular.module('starter.controllers', [])
.controller("ExampleController", function ($scope, $cordovaSQLite) {
$scope.selectAll = function(){
var query = "SELECT * FROM grocery1";
$cordovaSQLite.execute(db, query, []).then(function(res) {
if(res.rows.length > 0) {
alert("in query");
for(var i = 0; i < res.rows.length; i++) {
}
} else {
alert("no response");
}
}, function (err) {
alert("Error");
});
};
});
This is my database file gs.json, I generated this file using sqlite studio.i added some rows. i want to read these added rows.
{
"type": "database",
"name": "grocery",
"objects": [{
"type": "table",
"database": null,
"name": "grocery1",
"withoutRowId": true,
"ddl": "CREATE TABLE grocery1 (name CHAR (20))",
"columns": [{
"name": "name",
"type": "CHAR"
}],
"rows": [
[
"sdd"
],
[
"adddd"
],
[
"add"
],
[
"asd"
],
[
"aaa"
]
]
}]
}
Please help me how to read data from this file. I am getting error alert. The cursor not entering inside execute function. Is there any other way to read data from database file in ionic?
In one of my project I used this plugin and its working smooth in prod app too. Possible to try?
https://github.com/an-rahulpandey/cordova-plugin-dbcopy/blob/master/plugin.xml

Server always throws 403 on Angularjs ajax call in Django

Server always throws 403 in my Django app. I tried using csrf along with the data that is being posted to server, but still no luck. What am I missing ?
Here is how am invoking the $http service function
<body ng-controller="rdCtrl">
<a ng-click="saveprof()">Save</a>
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdCtrl', function ($scope, $http) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}
$scope.saveprof = function () {
//show spinner
$('.spinner').show();
$http.post('saveprof', {
data: { 'data': $scope.dataset},
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
$('#message').html(data);
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
});
</script>
</body>
Edit:
I corrected it, ajax call is being invoked when I click on button - but it returns 403 error.. Access forbidden.. I have view saveprof in my django views.. and also I used csrf token.. Am not sure why server returns 403. (http:/x.x.x.x/saveprof)
What am I missing?
you have to inject $http to the controller as parameter
app.controller('rdCtrl', function ($scope, $http) { .. }

Resources