When I am trying to upload pdf file, thumbnail is not showing after file upload. But it shows the thumbnail for video and ppt. I have created custom directive for thumbnail.
Here is my code,
my html code:
<div class="col-md-5" style="overflow: hidden">
<div style="display: inline-block" ng-if="thumbfilelink" ng-thumb="{ file: thumbfilelink, height: 100, width:75, fromServer:true, fileURL:thumbfilelink }"></div>
<div style="display:inline-block" ng-if="!thumbfilelink&&!item.isError">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading Preview...</span>
</div>
<span style="position: absolute; margin-left: 15px;" ng-bind="item.file.name"></span>
</div>
Controller:
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
$scope.$parent.delegate.onAttachmentUpload(response);
growl.addSuccessMessage($translate.instant('fileUpload.singlefileSuccess'));
// $scope.thumbfilelink=response.link;
$scope.thumbfilelink=$rootScope.app.coreURI +'file/image/'+response.id+'/preview';
};
Custom Directive:
return {
restrict: 'A',
template: '<div>' +
'<canvas class="ac-thumb" style="width:75px" />' +
'' +
'</div>',
transclude:true,
link: function (scope, element, attributes) {
if (!helper.support) return;
var canvas = element.find('canvas');
var reader = new FileReader();
if(params.fromServer) {
var img = new Image();
img.onload = onLoadImage;
img.src = params.fileURL;
}
else {
if (!helper.isFile(params.file)) return;
if (!helper.isImage(params.file)) return;
reader.readAsDataURL(params.file);
reader.onload = onLoadFile;
}
function onLoadFile(event) {
var img = new Image();
img.onload = onLoadImage;
img.src = event.target.result;
}
function onLoadImage() {
var width = params.width || this.width / this.height * params.height;
var height = params.height || this.height / this.width * params.width;
canvas.attr({width: width, height: height});
canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
} }
};
}]);
}).call();
you need to manipulate the event.
onChange event.
use on-change event, handle it as directive with passed controller function which will be called via bind.
Related
Here is my directive fileUpload for validation of image extenstion. I am not getting what is missing here. (Missing Required Controller Controller 'ngModel', required by directive 'fileUpload', can't be found! ) Please if any one can look in to this.
I found so many reference to the same question but no luck . please dont mark this as repeat question.
App.directive('fileUpload', function () {
return {
scope: true, //create a new scope
require: 'ngModel',
link: function (scope, el, attrs,ctrl) {
ctrl.$validators.images = function(modelValue, viewValue) {
console.log(modelValue);
console.log(viewValue);
};
ngModel.$setValidity('extension', true);
el.bind('change', function (event) {
var files = event.target.files;
var validFormats = ['jpg', 'jpeg', 'png', 'gif'];
var validSize = 500000;
for (var i = 0;i<files.length;i++) {
var ext = files[i].name.split('.');
var size = files[i].size;
if (ext !== undefined) {
var isExist = validFormats.indexOf(ext[1].toLowerCase()) >= 0 ? 1 : 0;
if (isExist == true && validSize >= (size)) {
ngModel.$setValidity('extension', true);
} else {
ngModel.$setValidity('extension', false);
}
}
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
});
Input :
<div class="form-group has-feedback" style="margin-left: 10px;">
<input name="file" type="file" ng-model="images" accept="image/*" multiple="true" file-upload />
<div style="color:grey; font-size: 12px;">
Extensions : jpg , jpeg , png , gif<br>
Size : 500KB
</div>
<div ng-messages="frmSupportPanelist.file.$error" ng-if="frmSupportPanelist.file.$touched">
<label id="message-required-error" class="validation-error-label" for="file" ng-message="extension">Please select valid Image </label>
</div>
</div>
How do I use $compile to get ng-click working on a block of code? My code currently displays a suggestion box when the parameters for a particular event are met. However, I want to let the user hide the suggestion box by clicking on the close button.
View
<textarea class="form-control suggest"
ng-keyup="vm.suggestActivate($event.keyCode)"
ng-mouseenter="vm.suggestActivate(32)"
rows="3"
ng-model="vm.summaryData"></textarea>
Controller
var vm = this;
var suggestionElement = document.createElement('div');
vm.suggestActivate = function(keyCode) {
if(keyCode === 32) {
if(vm.summaryData) {
var words = vm.words;
var suggestions = null;
suggestions = '<div style="padding-bottom: 20px"><strong>Suggested next word:</strong></div>'
for(var i = 0; i < 5; i++) {
suggestions += '<div style="padding-bottom: 20px">' + words[Math.floor(Math.random() * words.length)] + '</div>';
}
suggestions += '<div class="btn btn-default" ng-click="vm.suggestDeactivate()">Close</div>'
suggestionElement.innerHTML = suggestions;
suggestionElement.setAttribute('style', 'background: #B0B0B0; padding: 20px; position: relative; top: -3.9em; width: 25%');
suggestionElement.style.display = 'block';
var targetElement = event.srcElement;
targetElement.parentNode.appendChild(suggestionElement);
}
}
else {
suggestionElement.style.display = 'none';
}
};
try with $compile
targetElement.parentNode.appendChild($compile(suggestionElement)($scope));
mention that you have to inject $compile first.
ADD:
use angular.element to add new elements to DOM.
refer below demo:
angular.module("app", [])
.controller("myCtrl", function($scope, $compile) {
$scope.add = function() {
var strNewElement = document.createElement('div');
strNewElement.innerHTML = '<button ng-click="test()">Test</button>';
angular.element(event.srcElement.parentNode).append($compile(strNewElement)($scope));
};
$scope.test = function() {
alert('I am new element.');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<textarea ng-keypress="add()" rows="3"></textarea>
</div>
Can someone tell me why this code does not work?
this my preview area: <div class="preview"><img src="" alt=""></div>
and this my input:<input type="file" file-input> and follow my directive code:
var cmos = angular.module('cmos', ['simditor']);
// controller
cmos.controller('cmosCtrl', function( $scope ){}
// directive
cmos.directive("fileInput", function( $parse ){
return{
link: function($scope, element, attrs){
element.on('change', function(event){
var files = event.target.files;
var reader = new FileReader();
var img = document.querySelector(".preview > img");
reader.addEventListener("load", function(){
img.src = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}
// console.log(files[0]);
});
}
}
});
When I insert an image on input would like to take an image and show it to preview area.
you can use $scope like this..
<div class="preview"><img src="{{imageUrl}}" alt=""></div>
and in js.
var files = event.target.files;
var reader = new FileReader();
reader.addEventListener("load", function(){
$scope.imageUrl = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}
I have four mostly square looking charts which I need to resize on window resize. I have created a directive as below inside my angular controller at the top. This doesn't seem to work as the directive seem to executing as soon as the page loads and nothing seems to happen on resize. What am I missing here?
targetApp.directive('rsz', function ($window) {
return function (scope, element) {
var w = angular.element($window),
iw = w.innerWidth,
ih = w.innerHeight;
//resizing relative to the this parent container
scatterParentDimensions = getoffsetDimensions('#scatter-container'),
expectedWidth, expectedHeight;
console.log('rel w:', scatterParentDimensions.width, 'rel h:', scatterParentDimensions.height);
if (iw > ih) {
expectedWidth = scatterParentDimensions.width / 2;
expectedHeight = (scatterParentDimensions.height < iw)
? scatterParentDimensions.height / 2
: scatterParentDimensions.height / 4;
}
else {
expectedWidth = iw / 2;
expectedHeight = ih - 50;
}
// this is returning NaN as soon as the page is loaded.
console.log('set w:', expectedWidth, 'set h:', expectedHeight);
var selector = "#" + element.id;
if ($(selector).highcharts()) {
chart = $(selector).highcharts();
chart.setSize(expectedWidth, expectedHeight, false);
}
w.bind('resize', function () {
scope.$apply();
});
}
})
I have added the directive rsz on the four charts that need resizing.
//scatter.html
<div id="target-charts">
<div id="scatter-container" class="col-sm-8">
<div class="row">
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterA"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterB"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterC"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterD"></div>
</div>
</div>
</div>
</div>
</div>
Definition for getOffsetDimensions
function getoffsetDimensions(selector) {
var el = document.querySelector(selector);
return {
width: el.offsetWidth,
height: el.offsetHeight
}
}
in your directive, you listen to the resize event but didn't do anything (scope.$apply basically does nothing here).
you can either do the actually resizing inside of event handler, for example
myapp.directive('resize1', function($window) {
return function(scope, element, attr) {
var w = angular.element($window);
w.on('resize', function() {
var hh = document.getElementById('header').offsetHeight;
var fh = document.getElementById('footer').offsetHeight;
console.log('hh & fh', hh, fh);
var tp = hh + 2;
var bt = fh + 2;
console.log('tp & bt', tp, bt);
var changes = {
bottom: bt + 'px',
top: tp + 'px',
}
element.css(changes);
scope.$apply();
});
};
});
or watch the dimension changes, for example
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
scope.style = function () {
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
})
Eventually this is how I have made this work. It is still not the perfect solution and not at all generic, but I got it work for the initial stage of what I was looking for.
targetApp.directive('resize', function ($window) {
return function (scope, element, attr) {
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function (newValue, oldValue) {
var ew, eh, scatterParentDimensions = getoffsetDimensions('#scatter-container');
if (newValue.w > newValue.h) {
ew = scatterParentDimensions.width / 2;
eh = (scatterParentDimensions.height < newValue.w)
? scatterParentDimensions.height / 2
: scatterParentDimensions.height / 4;
}
else {
ew = newValue.w / 2;
eh = newValue.h - 50;
}
//resize highcharts
var selector = '#' + element[0].id;
var chart = angular.element(selector).highcharts();
chart.setSize(ew, eh, false);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
I have a requirement where user will upload their image and i have to convert it into something and send it to .Net REStful service. I am new to angular js. Could someone please help
Answer from here https://stackoverflow.com/a/24880314/625189
I would recommend you to use
https://github.com/ninjatronic/angular-base64.
After following instructions for using this library, you can simply
call:
var imageData=$base64.encode(image);
Don't forget to inject in your module:
.module('myApp', ['base64'])
You can use the angular custom directive to convert the image base64.
directive.js
myApp.directive('imgUpload', ['$rootScope',function (rootScope) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var canvas = document.createElement("canvas");
var extensions = 'jpeg ,jpg, png, gif';
elem.on('change', function () {
reader.readAsDataURL(elem[0].files[0]);
var filename = elem[0].files[0].name;
var extensionlist = filename.split('.');
var extension =extensionlist[extensionlist.length - 1];
if(extensions.indexOf(extension) == -1){
alert("File extension , Only 'jpeg', 'jpg', 'png', 'gif', 'bmp' are allowed.");
}else{
scope.file = elem[0].files[0];
scope.imageName = filename;
}
});
var reader = new FileReader();
reader.onload = function (e) {
scope.image = e.target.result;
scope.$apply();
}
}
}
}]);
Html:
<div class="input-group">
<input id="image" class="hidden" type="file" img-upload ng-model="imageName" name="imageName">
<img ng-src="{{image}}" height="100" width="100" ng-show="image"/>
<label for="image" class="btn btn-success btn-xs pull-center" name="upload" Value="">Upload Photo</label>
</div>
Now you need to add your code in controller which works for storing image or file in database.
If your image data is already in base64, try
<img alt="{{p.alt}}" data-ng-src="{{'data:image/png;base64,'+p.Photo}}" class="photo" />
Code to upload the image in 64 bit in Angularjs
Html code
<div class="col-md-8">
<img ng-src="data:image/png;base64,{{model.Logo}}" id="photo-id" />
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)" id="photo-upload" />
</div>
Angular code:
$scope.uploadFile = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function (e) {
$('#photo-id').attr('src', e.target.result);
var canvas = document.createElement("canvas");
var imageElement = document.createElement("img");
imageElement.setAttribute = $('<img>', { src: e.target.result });
var context = canvas.getContext("2d");
imageElement.setAttribute.load(function()
{
debugger;
canvas.width = this.width;
canvas.height = this.height;
context.drawImage(this, 0, 0);
var base64Image = canvas.toDataURL("image/png");
var data = base64Image.replace(/^data:image\/\w+;base64,/, "");
$scope.model.Logo = data;
});
}
}
}
for more go to link:
http://vikasbishtangular.blogspot.in/2017/04/code-to-upload-image-in-64-bit-in.html