How to display the image name of uploaded image in angularjs - angularjs

I am uploading an image and in one td I also put the image name. But my problem is when I upload a image, the image name repeats in all the rows which should not. What is wrong with this? Thanks.
This is my fiddle link: http://jsfiddle.net/DharkRoses/g31ykfy8/
sample code:
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function (files, index) {
if (files != null) {
var file = files[0];
var index = this.$index;
$scope.imgName = files[0].name;
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
$scope.thumbnail[index] = {dataUrl: e.target.result};
});
}
});
}
}
};

You need to create a same size of array for file names and based on index you need to push file names in photoChanged event.
Below is the working code for same.
angular.module('test', []);
angular.module('test').controller('UploadCtrl', function ($scope, $timeout,$parse) {
$scope.imgName ='';
$scope.thumbnail = {
dataUrl: []
};
$scope.fileNames = [,,,,];
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function (files, index) {
if (files != null) {
var index = this.$index;
var file = files[0];
$scope.fileNames[index] = files[0].name;
$scope.$apply();
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
$scope.thumbnail[index] = {dataUrl: e.target.result};
});
}
});
}
}
};
});
The markup looks something like below.
<div ng-app="test">
<div ng-controller="UploadCtrl">
<table>
<tr ng-repeat="i in [1, 2, 3, 4]">
<td>{{i}}</td>
<td>
<input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />
<img ng-src="{{ thumbnail[$index].dataUrl }}" height="50px" />
</td>
<td>
{{fileNames[$index]}}
</td>
</tr>
</table>
</div>
</div>
The working fiddle can be found here.

Related

TypeError: v2.UpdataData is not a function

I am new to Angular and MVC , and I have created a code for display
records into table view.
User can edit and delete that records by clicking the Edit and Delete
Link
but it shows me error when i click on edit link TypeError:
v2.UpdataData is not a function
and it also shows me error TypeError: $http.get is not a function
when i click on Delete Link
Can anyone help me to solve this out. Thanks in advance.
Controller.js
//update data of table
$scope.UpdataData = [];
//UpdateData();
$scope.UpdateData = function (StateMaster) {
var RetValData = DataService.UpdateStudent(StateMaster);
debugger;
getData.then(function (StateMaster) {
debugger;
StateID: $scope.StateID;
StateName: $scope.StateName;
CountryName: $scope.CountryName;
}, function () {
alert('Error in getting records');
});
}
$scope.DeleteData = [];
$scope.DeleteData = function (r, index) {
var retval = DataService.DeleteData(r.StateID).success(function (msg) {
$scope.countrydata.splice(index, 1);
alert('Student has been deleted successfully.');
}).error(function () {
alert('Oops! something went wrong.');
});
}.factory('DataService', function ($http) {
var fac={}
debugger;
fac.UpdateData= function($http)
{
return $http.get('/State/UpdateData');
}
return fac;
}).factory('DataService', function () {
var fac={}
debugger;
fac.DeleteData = function ($http)
{
return $http.get('/State/DeleteData');
}
return fac;
});
StateController.cs
public string UpdateData(StateMaster r)
{
if (r != null)
{
using (simpleEntities dbContext = new simpleEntities())
{
StateMaster lstdata = dbContext.StateMasters.Where(x => x.StateID == r.StateID).FirstOrDefault();
lstdata.StateName = r.StateName;
lstdata.CountryName = r.CountryName;
dbContext.SaveChanges();
return "Data Updated";
}
}
else
{
return "something went worng";
}
}
[HttpPost]
public string DeleteData(int id)
{
if (id != 0)
{
using (simpleEntities databContext = new simpleEntities())
{
var lsdata = databContext.StateMasters.Where(x => x.StateID == id).FirstOrDefault();
databContext.StateMasters.Remove(lsdata);
databContext.SaveChanges();
return "Data Deleted Successfully";
}
}
else {
return "Error Occured";
}
}
InsertState.cshtml
<div ng-app="MyApp" ng-controller="StateController">
<table class="table table-bordered">
<tr>
<td>Sr. No.</td>
<td>Country Name</td>
<td>State Name</td>
<td></td>
#*<td>Country Name</td>*#
</tr>
<tr ng-repeat="r in countrydata">
<td>{{$index + 1}}</td>
<td>{{r.CountryName}}</td>
<td>{{r.StateName}}</td>
#*<td>{{r.CountryName}}</td>*#
<td>
<span ng-click="UpdataData(r)" class="btnAdd">Edit</span> |
<span ng-click="DeleteData(r)" class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>
there is problem in you code with this
line $scope.UpdateData = function (StateMaster
as you are trying to run fuction of your $scop but fuction is of factory so you have to try like
factory.UpdateDate
Seem like there is problem in defining factory in angular , you can try below way
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
return {
sayHello: function(text){
return "Factory says \"Hello " + text + "\"";
},
sayGoodbye: function(text){
return "Factory says \"Goodbye " + text + "\"";
}
}
});
function HelloCtrl($scope, testService, testFactory)
{
$scope.fromFactory = testFactory.sayHello("World");
}
you can place your function and just try out it return you value or not

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

Unable to get $scope variables inside the fileReader.onload function

I am using something like this in angular
app.controller('techiesClub', function($scope, $http) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.asdf = "ankur";
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent, ss) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad, $scope);
}
}
});
Using uploadImage method on onchange of a input like this
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage()">
I am unable to get the srcData i.e. the base64 data into a variable that i can use else where.
Ankur,
We can rewrite html in this way.
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage(this);">
JS snippet here.. i'm trying with Blob version.
$scope.uploadImage = function ($event) {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = $event.files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var _ULR = window.URL || window.webkitURL;
var img = new Image();
img.onload = function() {
var srcData = this.src; // <--- data: blob
$scope.asdf = srcData; //////////////////NOT WORKING
};debugger;
img.src =_ULR.createObjectURL(fileToLoad);
}
}
I think you are missing the key point in your solution. I just change the way you are accessing the base64 contents. It should work.
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileReader.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad);
}
}

Angular upload file directive

I need a directive for upload file (brwose to choose file, and get it as binary data ) , in my angular application.
I use it a lot of times, so it has to be generic.
What is the best way to do it?
https://github.com/flowjs/ng-flow
This works fine.Of course some wrapping directive can be made at your side.
directive code
.directive("fileReaderGallery", ['background', function (background) {
return {
restrict: "E",
scope: true,
templateUrl: "templates/directive.html",
replace: true,
link: function ($scope, el, attrs) {
var input = null,
drag_image_gallery = el.find('.drag_image_gallery');
$scope.dragging = false;
$scope.fileselected = false;
$scope.uploaded = false;
$scope.uploading = false;
$scope.image = null;
$scope.clearFileReader = function () {
if (!attrs.styling || !input) return false;
$scope.formTitan.elementStyles[attrs.styling][$scope.styledItem.pt]['background-image'] = '';
$scope.formSelected[attrs.styling].imageFile = null;
$scope.formSelected[attrs.styling].isImage = false;
input.value = '';
$scope.fileselected = false;
$scope.imageName = '';
};
var readfiles = function (files) {
var reader, bg;
if (files && files[0]) {
if (files.length > 1) {
return console.log("Select single file only");
}
reader = new FileReader;
reader.onload = function (e) {
if (files[0].type.indexOf('image/') !== -1) {
if (e.target.result) {
bg = {
'background-image': e.target.result,
'background-repeat': 'repeat',
'background-position': 'top',
'background-size': ''
};
$scope.uploading = true;
$scope.$apply(function () {
background.add(angular.copy(bg));
$scope.current.dcBGImage = angular.copy(bg);
$scope.imageName = files[0].name;
$scope.image = e.target.result;
$scope.fileselected = true;
console.log(files[0])
});
}
} else {
return console.log('Please select an Image');
}
};
return reader.readAsDataURL(files[0]);
}
};
$scope.clickUpload = function () {
el.find('.bg-file-reader').click();
};
drag_image_gallery[0].ondragover = function () {
$scope.dragging = true;
//drag_image_gallery.addClass('ondragover');
$scope.$digest();
return false;
};
drag_image_gallery[0].ondragleave = function () {
$scope.dragging = false;
$scope.$digest();
//drag_image_gallery.removeClass('ondragover');
};
drag_image_gallery[0].ondrop = function (e) {
$scope.dragging = false;
$scope.$digest();
//drag_image_gallery.removeClass('ondragover');
e.preventDefault();
readfiles(e.dataTransfer.files);
};
el.find('.bg-file-reader').on('change', function () {
readfiles(this.files);
});
}
};
}]);
html template code
<div class="row upload_image text-center">
<div class="drag_image drag_image_gallery row text-center" ng-class=" {ondragover:dragging}">
Drag an Image here
</div>
OR
<div class="row text-center choose_computer">
<button ng-click="clickUpload()" class="btn btn-default">Choose from your computer</button>
<input type="file" class="bg-file-reader upload" name="gallery"/>
</div>
</div>
directive with drag and drop and chose file both functionality

convert image to base64 in angularjs

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

Resources