HTML 5 Drag & Drop with Angular 4 - html

I am trying to get the native HTML 5 drag & drop working in my angular app. I got the drag, fire the drag & the dragOver events, but the drop unfortunately doesn't fire anything. Here I have the HTML and drag events code below.
<ul *ngFor="let channel of channelList" >
<li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"
style="float:left; margin:0.5px" draggable="true" (dragstart)="drag(channel)">
<ng-container *ngIf="channel.compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}" width="100" height="100">
<img class="img-rounded" src="{{ channel.compChannel.compChannelLogo }}" alt="{{ channel.channel.compChannelName }}" width="100" height="100">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}"
width="100" height="100" >
</ng-template>
</li>
</ul>
<ul class="list-group" *ngFor="let channels of currentPickSelection" dropzone="copy">
<li class="list-group-item" style="float:Left; margin-left:0.5px" (dragover)="dragOver(channels[0])" (dragend)="drop(event)">
<ng-container *ngIf="channels[0].compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
<img class="img-rounded" src="{{ channels[0].compChannel.compChannelLogo }}" alt="{{ channels[0].compChannel.compChannelName }}"
width="70" height="70">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
</ng-template>
<br>
<strong>
<font size="2">{{ channels[0].pickCode }}</font>
</strong>
</li>
</ul>
drag(channel) {
console.log(channel);
}
dragOver(channel) {
this.draggedChannel = channel;
// console.log(this.draggedChannel);
}
drop(e) {
console.log(e);
}

I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:
drag.component.html:
<h2>Drag and Drop demo</h2>
<div id="div1"
(drop)="drop($event)"
(dragover)="allowDrop($event)">
<img
src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
draggable="true"
(dragstart)="drag($event)"
id="drag1"
width="88"
height="31">
</div>
<div id="div2"
(drop)="drop($event)"
(dragover)="allowDrop($event)">
</div>
drag.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'drag-root',
templateUrl: './drag.component.html',
styleUrls: ['./drag.component.css']
})
export class AppComponent {
drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
allowDrop(ev) {
ev.preventDefault();
}
drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
}
drag.component.css:
#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
Stackblitz example

<div (dragover)="onDragOver($event)"
(dragleave)="onDragLeave($event)" (drop)="onDrop($event)">
</div>
In your Component:
onDrop(event: any) {
event.preventDefault();
event.stopPropagation();
// your code goes here after droping files or any
}
onDragOver(evt) {
evt.preventDefault();
evt.stopPropagation();
}
onDragLeave(evt) {
evt.preventDefault();
evt.stopPropagation();
}

To use drag and drop in angular 4 application you can use npm module "ngx-uploader".
You will find the integration step from below link:
https://www.npmjs.com/package/ngx-uploader
All the imports parameter and classes you can take from the above link.
Here is my code for angular:
if (output.type === 'allAddedToQueue') { // when all files added in queue
// uncomment this if you want to auto upload files when added
const event: UploadInput = {
type: 'uploadAll',
url: API_BASE +'/api/uploads',
method: 'POST',
data:{total_files: this.files.length.toString()}
};
this.uploadInput.emit(event);
} else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
this.files.push(output.file);
} else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
// update current data in files array for uploading file
const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
this.files[index] = output.file;
} else if (output.type === 'removed') {
// remove file from array when removed
this.files = this.files.filter((file: UploadFile) => file !== output.file);
} else if (output.type === 'dragOver') {
this.dragOver = true;
} else if (output.type === 'dragOut') {
this.dragOver = false;
} else if (output.type === 'drop') {
this.dragOver = false;
}else if (output.type === 'done') {
if (output.file.response.status == 200) {
var uploaded_files = output.file.response.data;
this.propertyImage.push(uploaded_files);
}
else {
this.msgs = [];
this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
}
In the above code for output === done, you will get response from server side (In my case nodejs)
Below you can find the code for backend:
var formidable = require('formidable'),
http = require('http'),
util = require('util');
var form = new formidable.IncomingForm();
var src = './public/images/properties';
var dst_small = './public/images/properties/small'
var dst_medium = './public/images/properties/medium'
var validImage = false;
form.keepExtensions = true; //keep file extension
form.uploadDir = src;
form.onPart = function (part) {
if (!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {
validImage = true;
this.handlePart(part);
}
else {
validImage = false;
return res.json({ status: 404, msg: part.filename + ' is not allowed.' });
}
}
form.parse(req, function (err, fields, files) {
if (validImage) {
var image = files.file.path.split("/")[3];
var name = files.file.path.split("/")[3];
easyimg.rescrop({
src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
width: 100, height: 100,
cropwidth: 100, cropheight: 100,
x: 0, y: 0
}).then(
function (image) {
// console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
},
function (err) {
// console.log(err);
}
);
// for largeImage
easyimg.rescrop({
src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
width: 300, height: 300,
cropwidth: 300, cropheight: 300,
x: 0, y: 0
}).then(
function (image) {
// console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
return res.json({ status: 200, msg: 'Uploaded images', data: image });
},
function (err) {
console.log(err);
}
);
} else {
return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
}
});
Please change your image path according to your file path. I have used this code and it worked for me.
Hope the above code will help for you.
Thanks !!

Here is a solution on Angular 7:
Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.
First, import "DragAndDrop" module in your modules:
import {DragDropModule} from '#angular/cdk/drag-drop';
Then you just have to add "cdkDrag" directive to your HTML element:
<div class="example-box" cdkDrag>
Drag me around
</div>
Stackblitz (from material):
here
It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !

Simple but most powerful package
supports angular version >= 4.x
for documentation
for demo
How to use it?
Install
// if you use npm
npm install angular2-draggable
// or if you use yarn
yarn add angular2-draggable
Import
import { AngularDraggableModule } from 'angular2-draggable';
#NgModule({
imports: [
...,
AngularDraggableModule
],
})
export class AppModule { }
and finally use
// Basic Usage
<div ngDraggable>Drag Me!</div>

Use drop event. This will fire only when you drop a file.

This is this the way I got it working.
preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.
drag(channel) {
console.log(channel);
}
onDragOver(channel: any) {
console.log("Drag Over");
return false;
}
onDrop(e:any) {
console.log("Drop");
}

Related

vuesax The data of tables and buttons made with vue do not change. And when I click on the table, I get an error

I used vuesax.I'm using vuesax tables, but I have two problems.
First, there is a green button on the table. When I press this button, the button value should change, but it doesn't. However, the value changes are printed well in the console. html doesn't change. When you refresh, it changes.
Second, even if you press the buttons on pages 2, 3, and 4, only the buttons on page 1 work.I gave all the IDs differently or tried 'display none', but only the green button on the first page of the table always works.
Code referenced ▼
<template>
<component-to-re-render :key="componentKey" />
</template>
export default {
data() {
return {
componentKey: 0
}
},
methods: {
forceRerender() {
this.componentKey += 1
}
}
}
My code html ▼
<template>
<div :key="componentKey">
<vs-table class="rtable blank" id="repair" cellspacing="0">
<template #thead>
<vs-tr>
<vs-th> <p>설비코드</p></vs-th>
<vs-th> <p>교체일</p> </vs-th>
<vs-th> <p>소모품항목</p></vs-th>
<vs-th> <p>규격</p></vs-th>
<vs-th> <p>남은 점검일</p></vs-th>
<vs-th> <p>교체자</p></vs-th>
<!-- <vs-th> <p>비고</p></vs-th> -->
</vs-tr>
</template>
<template #tbody>
<vs-tr
:key="i"
v-for="(exchangedatasT, i) in $vs.getPage(exchangedatas1, page, max)"
:data="exchangedatasT"
class="tableColor"
:class="{
lastDay: todayGo2 !== todayGo2Go,
}"
>
<vs-td
><p>{{ exchangedatasT.Machinecd }}</p></vs-td
>
<vs-td
><p>{{ exchangedatasT.Exchangedt }}</p></vs-td
>
<vs-td
><p>{{ exchangedatasT.ExchangeItemnm }}</p></vs-td
>
<vs-td
><p>{{ exchangedatasT.Specnm }}</p></vs-td
>
<vs-td
class="pointer data99999"
:id="[`e${i}${page}`]"
#click="click2(i)"
v-if="exchangedatasT.CntDay == 99999"
>
<p>
<span>교체 완료</span>
</p>
</vs-td>
<vs-td
class="pointer data20"
:id="[`e${i}${page}`]"
#click="click2(i)"
v-else-if="exchangedatasT.CntDay > 20"
>
<p>
<span>점검 완료 : </span>
<span>{{ exchangedatasT.CntDay }}</span>
</p>
</vs-td>
<vs-td
class="pointer data10"
:id="[`e${i}${page}`]"
#click="click2(i)"
v-else-if="exchangedatasT.CntDay > 10"
>
<p class="">
<span>미점검 : </span>
<span>{{ exchangedatasT.CntDay }}</span>
</p>
</vs-td>
<vs-td
class="pointer dataElse"
:id="[`e${i}${page}`]"
#click="click2(i)"
v-else
>
<p>
<span>미점검 : </span>
<span>{{ exchangedatasT.CntDay }}</span>
</p>
</vs-td>
<vs-td
><p>{{ exchangedatasT.ExchangeUser }}</p></vs-td
>
<!-- <vs-td>{{ exchangedatasT.Remark }}</vs-td> -->
</vs-tr>
</template>
<template #footer>
<vs-pagination
v-model="page"
:length="$vs.getLength(exchangedatas1, max)"
/>
</template>
</vs-table>
</div>
</template>
My code js ▼
<script>
import Vue from "vue";
import Vuesax from "vuesax";
import "vuesax/dist/vuesax.css"; //Vuesax styles
import axios from "axios";
Vue.use(Vuesax, {
// options here
});
export default {
props: {
Rhatn3: String,
},
data: function () {
return {
page: 1,
max: 10,
Machinecd: "",
Exchangedt: "",
componentKey: 0,
};
},
watch: {
componentKey(newMsg) {
console.log("New msg: " + newMsg);
},
},
created() {
const vm = this;
axios
//소모품
.post("", {
Machinecd: "Test",
Exchangedt: vm.todayGo2,
})
.then((response) => {
console.log(vm.todayGo2);
vm.datas = response.data;
const entries = Object.values(response.data);
console.log(JSON.stringify(entries));
console.log(entries);
vm.exchangedatas1 = entries;
for (let i = 0; i < Object.keys(response.data).length; i++) {
// console.log(response.data);
this.ExchangeUser = response.data[i].ExchangeUser;
this.CntDay = response.data[i].CntDay;
if (this.currentNumber2 == i) {
axios
.post("", {
Machinecd: vm.datas[i].Machinecd,
ExchangeItem: vm.datas[i].ExchangeItem,
Spec: vm.datas[i].Spec,
ExchangeUser: vm.Rhatn3,
})
.then((response) => {
console.error(response);
})
.catch((error) => {
console.error(error);
});
// this.$router.go();
}
this.currentNumber2 = i;
}
})
.catch((error) => {
console.error(error);
});
axios;
},
methods: {
click2(i) {
const vm = this;
this.currentNumber2 = i;
// console.log(this.current Number);
this.componentKey += 1;
for (let i = 0; i < Object.keys(vm.exchangedatas1).length; i++) {
console.log(vm.datas[i].ExchangeItem);
// console.log(this.daydatas1[i]);
if (this.currentNumber2 == i) {
axios
.post("", {
Machinecd: vm.exchangedatas1[i].Machinecd,
ExchangeItem: vm.exchangedatas1[i].ExchangeItem,
Spec: vm.exchangedatas1[i].Spec,
ExchangeUser: vm.Rhatn3,
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
}
}
},
},
};
</script>

How to use component templates when creating a Nuxt app?

I am trying to create a dynamic header using Vue in a Nuxt application. However, the problem is two-fold:
1) I cannot get the template in the original DOM to be filled in with the template in the external file, which I was able to do by making the whole thing in .html files. I normally would use new Vue(el:...) for this, however even after including the latest version in the <head>, I cannot make that solution work.
2) I cannot get the proper data to display. When trying to insert the text, I can either get the index that I pass in, or it will error out.
My component that I am trying to pass in:
<template id="comp-dem-template">
<header-component>
<!-- Should call the function in "data" then replace the title. Instead has error about how it cannot search with 'in' -->
<span slot="pagetitle">
{{title}}
</span>
</header-component>
</template>
<script>
module.exports = {
el: '#header-component',
template: '<h1><slot name="pagetitle">Page Title Fallback</slot></h1>',
props: ['index'],
data: function () {
if (this.index == 0){
title: 'Index';
}
else if (this.index == 1){
title: 'Events';
}
else if (this.index == 2){
title: 'Policy';
}
else if (this.index == 3){
title: 'Frequently Asked Questions';
}
else if (this.index == 4){
title: 'Reservations';
}
else if (this.index == 5){
title: 'View Reservations';
}
else {
title: 'Make a Reservation';
}
}
}
</script>
And the place I am trying to pass it in to:
<head>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
</head>
<template>
<div class="container">
<logo />
<!-- This should be replaced with <h1><span>(name)</span></h1> according to my normal HTML version, however it doesn't here -->
<headercomponent index="0" />
<navbar/>
</div>
</template>
<script>
import Logo from '~/components/Logo.vue'
import headercomponent from '~/components/header-component.vue'
import navbar from '~/components/nav-bar.vue'
export default {
components: {
Logo,
headercomponent,
navbar
}
}
// Where I would normally try to insert it. However, even using the newest vue in the head won't let me do this ('Vue is not defined')
new Vue({ el: '#comp-dem-template' })
</script>
Your component has a lot of garbage, let's clean a little,
<template>
<span class="header-link">
{{ title }}
</span>
</template>
<script>
module.exports = {
name: 'header-component',
props: ['title']
}
</script>
<style>
.header-link {
}
</style>
You can call them using:
<header-component title="some text" />
in this way you keep the code clear and simple, but if you absolutely need send a index value here the component:
<template>
<span class="header-link">
{{ title }}
</span>
</template>
<script>
module.exports = {
name: 'header-component',
props: ['index'],
data: function() {
return {
title: ''
}
},
mounted: function() {
if (this.index === 0) {
this.title = 'Index'
} else if (this.index === 1) {
this.title = 'Events'
} else if (this.index === 2) {
this.title = 'Policy'
} else if (this.index === 3) {
this.title = 'Frequently Asked Questions'
} else if (this.index === 4) {
this.title = 'Reservations'
} else if (this.index === 5) {
this.title = 'View Reservations'
} else {
this.title = 'Make a Reservation'
}
}
}
</script>
<style>
.header-link {
}
</style>
use them like your example
<headercomponent index="0" />
the important part is understand the vue lifecycle, https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks, so Props not exist directly in data, but exist in mounted.

Adding a custom html tag in angular release 4 and greater

I've got a project I'm working on converting from an older version of angular to angular release 6. In the old project I had a custom html tag that was added as a directive. The html tag is :
<search-result-item item="item"></search-result-item>
The old js for this is :
'use strict';
(function() {
var searchResultItem = function($templateCache){
var controller = ['$scope', 'common.logModel', 'config', 'utilService', function($scope, Log, config, utilService){
var vm = this;
activate()
function activate(){
}
vm.getNumberOfWordsToShow = function (entry) {
if (typeof entry.numberOfWords === "undefined") {
return config.search.numberOfWordsShown;
}
else if (entry.numberOfWords === config.search.showAll) {
return config.search.showAllentry;
}
else {
return entry.numberOfWords;
}
}
vm.showMoreInfoLabel = function (entry) {
return (entry.details && entry.details !== null) ||
(entry.description.length > 0 && entry.description.length > config.search.numberOfWordsShown );
}
vm.showDetails = function (entry) {
entry.showDetails = !entry.showDetails;
entry.numberOfWords = entry.showDetails ? config.search.showAll : config.search.numberOfWordsShown;
}
vm.showMetadata = function (entry) {
utilService.openVoyagerLink(entry.pathToMetadata);
}
}];
return {
restrict: 'E',
replace: false,
scope: {
item: '='
},
controller: controller,
controllerAs: 'vm',
bindToController: true,
template: $templateCache.get('common/directives/searchresultitem/searchResultItem.tpl.html')
};
}
var commonModule = angular.module('commonModule');
commonModule.directive('searchResultItem', searchResultItem);
searchResultItem.$inject = ['$templateCache'];
}());
and the old html for this is :
<div class="row">
<div class="col-lg-9">
<div class="data-results-section">
<p class="search-result-url"><a ng-if="vm.item.path.substring(0,4) === 'http'" href="{{vm.item.path}}"
target="_blank">{{vm.item.path}}</a></p>
<div ng-if="vm.item.path.substring(0,4) !== 'http'">{{vm.item.path}}</div>
<p ng-show="vm.item.hasMetadata && vm.item.pathToMetadata.length > 0">
<a ng-click="vm.showMetadata(vm.item)" target="_blank">Metadata</a>
</p>
<p><span class="body-12-bold">Format: </span>{{vm.item.format}}</p>
<p><span class="body-12-bold">Indexed: </span>{{vm.item.indexed | date:'MM/dd/yyyy'}}</p>
<p><span class="body-12-bold">Relevance: </span>{{vm.item.score}}</p>
<p ng-show="vm.item.description.length > 0"><span>Description: </span>{{vm.item.description | htmlToPlaintext
| words : vm.getNumberOfWordsToShow(vm.item) }}
</p>
<div ng-show="vm.item.showDetails" ng-repeat="(key, val) in vm.item.details">
<p><span>{{key}}:</span>{{val}}</p>
</div>
<a class="search-result-view-more" href=""
ng-show="vm.showMoreInfoLabel(vm.item)"
ng-click="vm.showDetails(vm.item)">
<span ng-if="vm.item.showDetails">Hide</span>
<span ng-if="!vm.item.showDetails" class="links-14">View More Information</span> </a>
<!--links-14-->
</div>
<br>
</div>
<div class="col-lg-3">
<img class="search-result-img img-responsive"
ng-src="{{vm.item.thumbPath}}" fallback-img>
</div>
</div>
Any direction on examples of what to do on this as I'm having a hard time finding info for examples and documentation for this.
If you're porting it over to Angular code, you'll have to wrap all that up in a #Component, plenty of examples and description at https://angular.io/api/core/Component
In particular, you'll want to look at the selector parameter, as that allows you to specify how to reference it in the html. Specific to your example might look like
#Component({
selector: 'search-result-item'
...
Then you'd reference it the same with <search-result-item>

Get image dimension in angular 2

I am writing code to upload an image file. I need to know the dimensions(height and width) of the image that will be uploaded before I call the function to upload.
Is there a way in angular 2 by which I can extract the image dimension? If so, how?
I created function to get image size
getImgSize(imageSrc: string): Observable<ISize> {
let mapLoadedImage = (event): ISize => {
return {
width: event.target.width,
height: event.target.height
};
}
var image = new Image();
let $loadedImg = fromEvent(image, "load").pipe(take(1), map(mapLoadedImage));
// Rxjs 4 - let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage);
image.src = imageSrc;
return $loadedImg;
}
interface ISize { width: number; height: number; }
Also you can subscribe on load event in html
<img (load)="loadedImg($event)" [src]="imageSrc"> and get size from it.
With the Angular2 approach, I'll create a custom directive to get the height and width of any element. For img, I'll apply it(directive) in the img tag and whenever I want to get the height & width of an img, I just need click it. You can modify according to your need.
DEMO : https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
directive.ts
import { Directive,Input,Output,ElementRef,Renderer} from '#angular/core';
#Directive({
selector:"[getHeightWidth]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight);
console.log('width---' + this.el.nativeElement.offsetWidth);
}
}
app.ts
#Component({
selector: 'my-app',
template: `
<div style="width:200px;height:300px">
<img getHeightWidth <!-- here I'm using getHeightWidth directive-->
[src]="source" alt="Angular2"
width="100%"
height="100%">
</div>
`,
})
export class AppComponent {
source='images/angular.png';
}
Simply you can use following code to get the width and height (Resolution) of the Image.
HTML Code
<img #pic [src]="imgURL" (load)="onLoad()>
In Angular
#ViewChild('pic', { static: false }) pic: ElementRef;
onLoad() {
console.log((this.pic.nativeElement as HTMLImageElement).naturalWidth);
console.log((this.pic.nativeElement as HTMLImageElement).naturalHeight);
}
In case if you need to get the image size in ts file:
getImageDimension(image): Observable<any> {
return new Observable(observer => {
const img = new Image();
img.onload = function (event) {
const loadedImage: any = event.currentTarget;
image.width = loadedImage.width;
image.height = loadedImage.height;
observer.next(image);
observer.complete();
}
img.src = image.url;
});
}
Call above method:
const image = {
url: 'https://kalgudi.com/store/assets/images/e-mahila1.jpg',
context: 'Mahila self help group'
}
this.getImageDimension(image).subscribe(
response => {
console.log(response);
}
);
In component.ts
this.uploadService.validateandUploadFile(files, 300, 300);
In service.ts file
import { Injectable } from '#angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { BehaviorSubject } from 'rxjs';
FOLDER = '/';
imageUrl = "";
resData: BehaviorSubject<any> = new BehaviorSubject(null);
data = { message: "", data: "" };
constructor() { }
validateandUploadFile(file, Iheight, Iwidth) {
let fileToUpload = file;
if (fileToUpload.type == "image/jpeg" || fileToUpload.type == "image/png" || fileToUpload.type == "image/jpeg") {
//Show image preview
let reader = new FileReader();
reader.onload = (event: any) => {
var img = new Image();
img.onload = () => {
let width = img.width;
let height = img.height;
if (width <= Iwidth && height <= Iheight) {
this.imageUrl = event.target.result;
this.uploadfile(file);
} else {
this.data.message = "You can maximum upload " + Iheight + " * " + Iwidth + " File";
this.data.data = "";
this.resData.next(this.data);
return this.resData;
}
};
img.src = event.target.result;
}
reader.readAsDataURL(fileToUpload);
} else {
this.data.message = "You can't be able to upload file except JPG and PNG format";
this.data.data = "";
this.resData.next(this.data);
return this.resData;
}
}
uploadfile(file) {
if (file != null) {
const bucket = new S3(
{
accessKeyId: '***********************',
secretAccessKey: '**********************************',
region: 'us-east-2'
}
);
const params = {
Bucket: '*********',
Key: file.name,
Body: file,
ACL: 'public-read'
};
var that = this;
bucket.upload(params, function (err, data) {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
console.log('Successfully uploaded file.', data);
that.data.message = "Successfully uploaded file.";
that.data.data = data.Location;
that.resData.next(that.data);
return that.resData;
});
}
}
You have to use JS code to find the height and width of image as follow :
<!DOCTYPE html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function readURL(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image1')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function upload()
{
var img = document.getElementById('image1');
var width = img.clientWidth;
var height = img.clientHeight;
alert(width + " : " + height);
//check height and width using above two variables (width/height) in if block and place upload code in if block...
}
</script>
</head>
<body>
<input type='file' onchange="readURL(this);" /><input type="button" value="Upload" onClick="upload()" /><br>
<img id="image1" src="#" alt="your image" height="auto" width="auto" />
</body>
</html>
In above code we have to place selected image in image element, after during upload process check height and width and process to upload.
Thanks...

angular working on plunker but not work on browser or emulator

i have created ionic project with slidemenu. I also created custom reusable directive where I am getting data from rest api and assigning its value to directive for ng-repeat, it is like dropdown but it items open in modal popup. So when I select value from first directive,I will filter another rest api to assign data to same directive for another instance.
In that I have input box act as filter which filter for ng-repeat items
Now issue starts in first directive filter works very good but second directive filter will not work. When I filter than all items will get clear and I remove value from input box than still items will not appear back.
First I thought that my first directive json object is 1 level that is the reason it is working and second directive json is nested object.
So I created plunker with same exact code which works like charm but it does not work on desktop or emulator.
can somebody tell me what can be the issue. I am not putting plunker link as it working very good, so it is worthless
Directive code
angular.module('plexusSelect', []).directive('plexusSelect', ['$ionicModal',
function($ionicModal) {
// Runs during compile
return {
scope: {
'items': '=',
'text': '#',
'textIcon': '#',
'headerText': '#',
'textField': '#',
'textField2': '#',
'valueField': '#',
'callback': '&'
},
require: 'ngModel',
restrict: 'E',
templateUrl: 'templates/plexusSelect.html',
link: function($scope, iElm, iAttrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
$scope.allowEmpty = iAttrs.allowEmpty === 'false' ? false : true;
$scope.defaultText = $scope.text || '';
$ionicModal.fromTemplateUrl('plexusSelectItems.html', {
'scope': $scope
}).then(function(modal) {
$scope.modal = modal;
$scope.modal['backdropClickToClose'] = false;
});
$scope.showItems = function($event) {
$event.preventDefault();
$scope.modal.show();
}
$scope.hideItems = function() {
$scope.modal.hide();
}
/* Destroy modal */
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.viewModel = {};
$scope.clearSearch = function() {
$scope.viewModel.search = '';
}
/* Get field name and evaluate */
$scope.getItemName = function(field, item) {
return $scope.$eval(field, item);
}
$scope.validateSingle = function(item) {
$scope.text = $scope.$eval($scope.textField, item) + ($scope.textField2 !== undefined ? " (" + $scope.$eval($scope.textField2, item) + ")" : "");
$scope.value = $scope.$eval($scope.valueField, item);
$scope.hideItems();
if (typeof $scope.callback == 'function') {
$scope.callback($scope.value);
}
ngModel.$setViewValue($scope.value);
}
$scope.$watch('text', function(value) {
if ($scope.defaultText === value) $scope.placeholder = 'placeholderGray';
else $scope.placeholder = 'placeholderBlack';
});
}
};
}
])
Directive html
<ion-list>
<ion-item class="item-text-wrap item" ng-click="showItems($event)">
<a class="item-icon-left item-icon-right">
<i class="icon {{textIcon}} placeholderGray"></i>
<span class="{{placeholder}}">{{text}}</span>
<i class="icon ion-chevron-right"></i>
</a>
</ion-item>
</ion-list>
<script type="text/ng-template" id="plexusSelectItems.html">
<ion-view class="select-items modal">
<ion-header-bar class="bar-positive" has-subheader="true">
<button ng-click="hideItems()" class="button button-positive button-icon ion-ios7-arrow-back"></button>
<h1 class="title">{{headerText}}</h1>
</ion-header-bar>
<ion-header-bar class="bar-light bar-subheader bar bar-header item-input-inset">
<div class="item-input-wrapper">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="viewModel.search" placeholder="select city...">
<button ng-show="viewModel.search.length" ng-click="clearSearch()" class="customIcon button button-icon ion-close-circled input-button"></button>
</div>
</ion-header-bar>
<ion-content>
<div class="list">
<label ng-repeat="item in items | filter:viewModel.search" class="item item-text-wrap" ng-click='validateSingle(item)'>
{{getItemName(textField, item)}} {{textField2 !== undefined ? " (" + getItemName(textField2, item) + ")" : ""}}
</label>
</div>
</ion-content>
</ion-view>
</script>
My Controller
.controller('SearchCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get("http://xxxx/lists/getbytitle('xxx')/items?$select=City_Code,City_Name_EN&$filter=Active eq 1&$orderby=City_Name_EN asc", {
headers: {
Accept: "application/json;odata=verbose"
}
}).then(function(resp) {
$scope.deptStations = resp.data.d.results;
}, function(err) {
console.log(err);
});
$scope.deptStation = {
value: null
};
$scope.arrStation = {
value: null
};
$scope.$watch('deptStation.value', function(deptStation) {
$http.get("http://xxx/lists/getbytitle('xxx')/items?$select=Destination/City_Code,Destination/City_Name_EN&$expand=Destination/City_Code,Destination/City_Name_EN&$filter=Origin/City_Code eq '" + deptStation + "'&$orderby=Destination/City_Name_EN asc", {
headers: {
Accept: "application/json;odata=verbose"
}
}).then(function(resp) {
$scope.arrStations = resp.data.d.results;
}, function(err) {
console.log(err);
});
});
}
]);
My First Directive JSON
{"d":{"results":[{"City_Name_EN":"Abu Dhabi","City_Code":"AUH"},{"City_Name_EN":"Alexandria","City_Code":"HBE"},{"City_Name_EN":"Amman","City_Code":"AMM"},{"City_Name_EN":"Bahrain","City_Code":"BAH"},{"City_Name_EN":"Bangkok","City_Code":"BKK"}]}}
My Second Directive JSON
{"d":{"results":[{"Destination":{"City_Code":"HBE","City_Name_EN":"Alexandria"}},{"Destination":{"City_Code":"BKK","City_Name_EN":"Bangkok"}},{"Destination":{"City_Code":"MAA","City_Name_EN":"Chennai"}},{"Destination":{"City_Code":"COK","City_Name_EN":"Cochin"}}]}}
Really I hate this but it turnout to be a bug in new version.
On plunkr I was referencing 1.0.0-beta.1 ionic.bundle.min.js
And in my project I was referencing latest version which is 1.0.0-beta.14 ionic.bundle.min.js
Once I replace same version js file of my project to plunkr reference, it start behaving same as it is on my project.