Am using the following module https://github.com/danialfarid/ng-file-upload and it has well documented except for aborting the upload process. During uploading the files, The code for cancel the upload is not working fine.
Am getting error that says 'abort is not a function' and I do not know how to apply the abort() function to cancel the upload process.
I dont know what i missed here, Could anyone give me some idea on why? or any suggestion please.
My html
<body ng-app="fileUpload" ng-controller="MyCtrl">
<h4>Upload on file select</h4>
<button ngf-select="uploadFiles($files)" multiple
accept="image/*,audio/*,video/*">Select Files</button>
<span class="progress" ng-show="progress >= 0">
<div style="width:{{progress}}%" ng-bind="progress + '%'"></div>
</span>
{{errorMsg}}
<button ng-click="cancelUpload()">Cancel</button>
</body>
JS(Angular)
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
var upload = "";
$scope.uploadFiles = function (files) {
$scope.files = files;
if (files && files.length) {
upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {
files: files
},
resumeSize: function() {return promise;}
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function (evt) {
$scope.progress =
Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
$scope.cancelUpload = function(files){ // here is my cancel program
console.log("Cancelling");
upload.abort(); // this 'abort()' is not working as mentined
}
Related
My problem started when I tried to add a library SignalR in my AngularJs project. I do not know why but the data flow has stopped working properly, I mean that when I try to insert an object into an array I do not see it, but when I try to add another one I see first object, and when I try to add a third object I see only the second.
edit : all code in the angular controller.
app.controller('HomeCtrl', ['$scope', 'HttpSrv', '$state', function ($scope, HttpSrv, $state) {
$scope.messages = [];
activate();
function activate() {
if (HttpSrv.CheckToken()) {
loadPage();
}
};
$scope.$on("$destroy", function () {
con.stop();
});
function connectToChat() {
HttpSrv.http('GET', 'home/GetChatToken').then(function (res) {
localStorage.setItem('ChatToken', res.Result);
con.start({ jsonp: true }, function () { console.log('Start'); });
});
}
var con = $.hubConnection("http://localhost:4704/");
var hub = con.createHubProxy('ChatHub');
hub.on('fail', function (res) {
console.error(res);
});
hub.on('addMessage', addMessage);
$scope.trySend = function () {
hub.invoke('SendMessage', localStorage.getItem('ChatToken'), document.getElementById('messageBox').value);
};
function addMessage(name, message, elementId) {
var tempMessage = '<li id="' + elementId + '" class="right clearfix"><div class="chat-body clearfix">'
tempMessage += '<div class="header"><strong class="pull-left primary-font">' + name + ': </strong> <br />'
tempMessage += '</div><p>' + message + '</p></div></li>'
document.getElementById('chatBody').innerHTML += tempMessage;
document.getElementById('messageBox').value = '';
document.getElementById(elementId).scrollIntoView();
document.getElementById('chatBody').focus();
}
function loadPage() {
HttpSrv.http('GET', 'home/get').then(function (res) {
//console.log(res);
if (res.Status == 200 && res.Succeeded) {
connectToChat();
for (var i = 0; i < res.ListResult.length; i++) {
res.ListResult[i].CreateDate = res.ListResult[i].CreateDate.replace('T', ' ').slice(0, 19);
}
$scope.newsList = res.ListResult;
}
});
};}]);
(i use document.getElementById because of the problem)
First, you shouldn't be building markup in your code. Simply add the message to the list and use ng-repeat in your markup.
However, you also must make sure you use $scope.$apply() or $scope.$digest() when you are processing messages from signalR.
function addMessage(name, message, elementId) {
$scope.$apply(function(){
$scope.messages.push(message);
});
}
I want to take screenshot with cordova-screenshot-plugin. Can i save that picture as variable or something so i can manipulate with it later? Service for taking screenshot :
.service('$cordovaScreenshot', ['$q', function($q) {
return {
capture: function(filename, extension, quality) {
extension = extension || 'jpg';
quality = quality || '100';
var defer = $q.defer();
console.log(defer);
navigator.screenshot.save(function(error, res) {
if (error) {
console.error(error);
defer.reject(error);
} else {
console.log('screenshot saved in: ', res.filePath);
defer.resolve(res.filePath);
}
}, extension, quality, filename);
return defer.promise;
}
};
}]);
I will try to take screenshot with button, and show it with popup.
The Cordova-Plugin-Screenshot API gives you the file path of the picture. This filepath is accessible from anywhere in the smartphone. So you could use the sample service given in the official github repository with something like that in your controller:
// app is define elsewhere in your application
app.controller('Awesome.Controller', AwesomeController);
AwesomeController.$inject = ['$cordovaScreenshot'];
function AwesomeController($cordovaScreenshot) {
var vm = this;
vm.onClick = takeScreenshot;
function takeScreenshot() {
$cordovaScreeshot.capture('mypic', 'jpg', 80).then(function(filepath) {
vm.filepath = filepath;
}
}
}
With an HTML template like this:
<button on-click="vm.onClick()">take screenshot</button>
<div ng-if="vm.filepath">
<p>Result: {{vm.filepath}}</p>
<img ng-src="{{vm.filepath}}>
</div>
Is there a way to access a file from a type="file" input in javascript?
The purpose is to send it with XHR afterwards.
Example :
<input type="file" id="myFile"/>
var file = $('#myFile');
With AngularJS :
<input type="file" file-changed/>
.directive('fileChanged', function(){
return {
link : function(scope, element){
element.on('change', function(e){
if(e.target.value != ""){
scope.myCtrl.file = e.target;
}
});
}
}
)
.controller('myCtrl', function(){
var self = this;
self.file;
//self.file should be available here for XHR.
});
Global need :
Multiple input type files needs to be send to a REST api.
I need to keep track of the progress of each file upload, WITHOUT using an external libary.
This can be accomplished easily through FileReader
This is well supported these days http://caniuse.com/#feat=filereader
Here is a snippet of code from HTMLGoodies that will help you get started ::
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert("Got the file.n" + "name: " + f.name + "n" + "type: " + f.type + "n" + "size: " + f.size + " bytesn" + "starts with: " + contents.substr(1, contents.indexOf("n")));
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
You can use this directive below to attach the file to some $scope variable:
HTML:
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">Upload</button>
DIRECTIVE:
angular.module('yourApp').directive('fileModel', ['$parse', function ($parse) {
"use strict";
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel),
modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
CONTROLLER:
$scope.uploadFile = function () {
var file = $scope.myFile,
uploadUrl = "URL://";
fileUploadService.uploadFileToUrl(file, uploadUrl, function (err, data) {
$scope.ret = err || data;
});
};
Hope this helps.
I am trying to bind from a http get request. The http get is returning true or false. I have tested the get and it is returning properly. When I run the code below, it shows the alert(1111) properly also. However, when I'm trying to change the button text, nothing appears! I have tried everything that I know to do. Any advice would be helpful.
Post.js
myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {
var status = "";
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
$scope.statusMessage = data;
} else {
//Following - show Follow
$scope.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}]);
Html
<span style="float: right" ng-controller="FollowController as follow">
<button type=" button" class="btn btn-success" onclick="location.href='#Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
{{ follow.statusMessage }}</button>
</span>
You should bind the variables to this instead of $scope as you are using controllerAs approach
Controller
myApp.controller('FollowController', ['$scope', '$http',
function($scope, $http) {
var status = "";
var follow = this;
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
follow.statusMessage = data;
} else {
//Following - show Follow
follow.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}
]);
I'm just trying to get this to work:
.....
.when('/channel/:id/:slug',{
templateUrl:'views/channel/index.html',
controller:'Channel',
publicAccess:true,
sessionAccess:true
})
.....
app.controller('Channel', ['$scope','$routeParams', function ($scope,$routeParams) {
}]);
app.run(function($rootScope, $location, $route) {
var routesOpenToSession = [];
angular.forEach($route.routes, function(route, path) {
console.log(path);
console.log(route);
route.sessionAccess && (routesOpenToSession.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
var closedToSession = (-1 === routesOpenToSession.indexOf($location.path()));
if(closedToSession && $rootScope.session.id_user) {
$location.path('/');
}
});
});
why i can't access the page via site.com/channel/9/my-slug also if $rootScope.session.id_user exists and sessionAccess:true ?
i get redirected to / , while any other static url are ok using sessionAccess:true for example channel/staticparam is ok but with dynamic params it won't work
this is the console log result :
fixed sorry for the stupid question:
/*Not logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location,$route) {
var routesOpenToPublic = [];
angular.forEach($route.routes, function (route, path) {
if(route.publicAccess){ routesOpenToPublic.push(route.regexp); }
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not logged users users
if(routesOpenToPublic.indexOf(next_url_regexp) < 0){
$location.path('/auth/login');
}
});
}]);
/*Logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location, $route) {
if($rootScope.session && $rootScope.session.id_user){
var routesOpenToSession = [];
angular.forEach($route.routes, function (route, path) {
if(route.sessionAccess){ routesOpenToSession.push( route.regexp);}
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not allowed session users
if(routesOpenToSession.indexOf(next_url_regexp) < 0){
$location.path('/');
}
});
}
}]);
i needed to check the route regexp and not the static url path