ionic cordova encrypt base64 image - javascript

I have this app where I take picture with cordova camera then move it into file-system , save the imgpath for the image into sqlite db and display it, I'm trying to encrypt the imgPath for the image which is saved on ccordova.file.data directory , I tried cordova safe plugin https://github.com/disusered/cordova-safe ,
but I keep getting "Error with cryptographic operation".
Any help would be appreciated
var db = null;
angular.module('starter', ['ionic', 'ngCordova']) 
.run(function($ionicPlatform, $cordovaSQLite) {    
$ionicPlatform.ready(function() {      
try {        
db = $cordovaSQLite.openDB({          
name: "my.db",
          location: 'default'        
});        
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS imageTable " + "(id integer primary key, image text)");      
} catch (e) {        
alert(e);      
} finally {       }
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('ImageCtrl', function($scope, $rootScope, $state, $stateParams, $cordovaDevice, $cordovaFile, $ionicActionSheet, $cordovaCamera, $cordovaFile, $cordovaDevice, $ionicPopup, $cordovaActionSheet, $cordovaSQLite, $interval) {
var imagesP = [];
//$scope.images = [];
$scope.showAlert = function(title, msg) {
var alertPopup = $ionicPopup.alert({
title: title,
template: msg
});
};
$scope.loadImage = function() {
var options = {
title: 'Select Receipts Image ',
buttonLabels: ['Gallery', 'Take photo', 'File System'],
addCancelButtonWithLabel: 'Cancel',
androidEnableCancelButton: true,
};
$cordovaActionSheet.show(options).then(function(btnIndex) {
var type = null;
if (btnIndex === 1) {
type = Camera.PictureSourceType.PHOTOLIBRARY;
} else if (btnIndex === 2) {
type = Camera.PictureSourceType.CAMERA;
}
if (type !== null) {
$scope.selectPicture(type);
}
});
}
// Take image with the camera or from library and store it inside the app folder
// Image will not be saved to users Library.
$scope.selectPicture = function(sourceType) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
correctOrientation: true,
targetWidth: 800,
targetHeight: 800,
popoverOptions: CameraPopoverOptions, // for IOS and IPAD
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
// alert(currentName);
//Create a new name for the photo to avoid duplication
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
//alert(newFileName);
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
$scope.encryptFile(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
// alert( fileEntry.nativeURL);
};
});
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
//$scope.images.push(newFileName);
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
}
},
function(err) {
// Not always an error, maybe cancel was pressed...
})
};
$scope.add = function(path) {             
if (imagesP != null) {          
$cordovaSQLite.execute(db, "INSERT INTO imageTable (images) VALUES(?)", [path] );        
}        
alert("Inserted.");      
},
function(e) {        
alert(e);      
};
$scope.encryptFile = function(file){
var safe = cordova.plugins.disusered.safe,
key = 'someKeyABC';
function success(encryptedFile) {
console.log('Encrypted file: ' + encryptedFile);
}
function error() {
console.log('Error with cryptographic operation');
}
safe.encrypt(file, key, success, error);
}
  
$scope.ShowAllData = function() {     
$scope.images = [];      
$cordovaSQLite.execute(db,"SELECT images FROM imageTable").then(function(res) {          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({                
id: res.rows.item(i).id,
image: res.rows.item(i).images
              
});            
}          
}        
},         function(error) {          
alert(error);        
}      );
 
} 
       

Related

AngularJS - Get Checkbox Value?

I'm trying to add a function in my JS for a basic ToDo app that I'm working on using Angular Material and I need to know how I can get it to read the value/property of an md-checkbox (whether or not it is ticked).
The reason for this is I'm trying to make an alert appear informing the user that they need to select at least one checkbox if none are currently selected and they click on the Delete button at the bottom.
Anyone know how I could do this?
Codepen: http://codepen.io/anon/pen/QpdpEa.
JS:
var app = angular.module('todoApp', ['ngMaterial']);
function menuController ($scope, $mdDialog) {
var originatorEv;
this.openMenu = function($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
};
app.controller('todoController', function($scope, $mdDialog, $mdToast) {
$scope.sortBy = '-addedOn';
$scope.taskList = [
{ name: 'Task 1', completed: false, addedOn: 1488722128000 },
{ name: 'Task 2', completed: false, addedOn: 1488722128000 },
];
$scope.addTask = function() {
if (angular.isUndefined($scope.taskName) || $scope.taskName.length === 0) {
var alert = $mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('Error')
.textContent('You must enter a task name')
.ok('Close');
$mdDialog.show( alert )
.finally(function() {
alert = undefined;
});
}
else {
$scope.taskList.push({name: $scope.taskName, addedOn: Date.now()});
$scope.taskName = "";
var pinTo = $scope.getToastPosition();
$mdToast.show (
$mdToast.simple()
.textContent('Task Added')
.position(pinTo)
.hideDelay(3000)
)
}
};
$scope.selectAll = function() {
angular.forEach($scope.taskList, function(task) {
task.completed = true;
});
};
$scope.selectNone = function() {
angular.forEach($scope.taskList, function(task) {
task.completed = false;
});
};
$scope.delete = function(ev) {
var confirm = $mdDialog.confirm()
.title ('Are you sure you want to delete the selected tasks?')
.textContent ('Deleted tasks can\'t be recovered.')
.targetEvent (ev)
.ok ('Confirm')
.cancel ('Cancel')
clickOutsideToClose: false;
$mdDialog.show(confirm).then(function() {
var pinTo = $scope.getToastPosition();
$mdToast.show (
$mdToast.simple()
.textContent('Tasks Deleted')
.position(pinTo)
.hideDelay(3000)
)
$scope.status = 'Tasks Deleted';
var i = $scope.taskList.length;
while (i--) {
var task = $scope.taskList[i];
if(task.completed) {
$scope.taskList.splice(i, 1);
}
}
},
function() {
$scope.status = 'Deletion Cancelled';
});
};
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
};
var last = {
bottom: false,
top: true,
left: false,
right: true
};
$scope.toastPosition = angular.extend({},last);
$scope.getToastPosition = function() {
sanitizePosition();
return Object.keys($scope.toastPosition)
.filter(function(pos) { return $scope.toastPosition[pos]; })
.join(' ');
};
function sanitizePosition() {
var current = $scope.toastPosition;
if ( current.bottom && last.top ) current.top = false;
if ( current.top && last.bottom ) current.bottom = false;
if ( current.right && last.left ) current.left = false;
if ( current.left && last.right ) current.right = false;
last = angular.extend({},current);
};
});
app.controller('toastController', function($scope, $mdToast) {
$scope.closeToast = function() {
$mdToast.hide();
}
});
HTML:
<md-card-actions layout="row" class="md-padding">
<md-button ng-click="selectAll()" class="md-raised md-primary">Select All</md-button>
<md-button ng-click="selectNone()" class="md-raised md-primary">Select None</md-button>
<md-button ng-click="delete()" class="md-raised md-warn md-hue-2">Delete</md-button>
</md-card-actions>
You can just iterate over the taskList variable and check if at least one element has property completed with true value.
I've added a custom function, binded to the Show button. If you click on it, you will see in the console true if there's at least one checkbox checked or false if none of the checkboxes is checked.
$scope.show = function(){
console.log($scope.taskList.some(v => v.completed))
}
http://codepen.io/anon/pen/BWpWmw?editors=1010
I've made changes to your code that you can see & run here: http://codepen.io/anon/pen/jBymPd?editors=1010
I'm using the $filter service to get the task(s) that have completed member set to true.
If nothing has been checked, then you can show an alert to at-least select one task to delete. If one or more task is checked, then you just delete them.
The new changes in your code are shown below:
app.controller('todoController', function($scope, $mdDialog, $mdToast, $filter) {
$scope.delete = function(ev) {
var completedTasks = $filter('filter')($scope.taskList, { completed: true}, true);
console.log(completedTasks); // array of completed tasks, can be empty.
if (completedTasks.length > 0) {
console.log('show dialog box to confirm');
// your existing code.
var confirm = $mdDialog.confirm()
.title ('Are you sure you want to delete the selected tasks?')
.textContent ('Deleted tasks can\'t be recovered.')
.targetEvent (ev)
.ok ('Confirm')
.cancel ('Cancel')
clickOutsideToClose: false;
$mdDialog.show(confirm).then(function() {
var pinTo = $scope.getToastPosition();
$mdToast.show (
$mdToast.simple()
.textContent('Tasks Deleted')
.position(pinTo)
.hideDelay(3000)
)
$scope.status = 'Tasks Deleted';
var i = $scope.taskList.length;
while (i--) {
var task = $scope.taskList[i];
if(task.completed) {
$scope.taskList.splice(i, 1);
}
}
},
function() {
$scope.status = 'Deletion Cancelled';
});
} else {
alert('please select at-least one task to delete');
console.log('show alert to check at-least one task');
}
};
});

'jsonp' is undefined(AngluarJS with PubNub)

I'm learning Angular and creating a chat app using the PubNub lib then I get this error when I navigate to the page where I can create room or join a chat.
TypeError: Cannot read property 'jsonp' of undefined
at window.PUBNUB.CREATE_PUBNUB (https://cdn.pubnub.com/pubnub-3.7.20.js:2719:14)
at new SELF (https://cdn.pubnub.com/pubnub-3.7.20.js:2739:16)
at a.exports.e.value (http://localhost:9000/bower_components/pubnub-angular/dist/pubnub-angular-3.1.0.min.js:16:64)
at Object.b.init (http://localhost:9000/bower_components/pubnub-angular/dist/pubnub-angular-3.1.0.min.js:4:87)
at new <anonymous> (http://localhost:9000/scripts/controllers/main.js:13:15)
at invoke (http://localhost:9000/bower_components/angular/angular.js:4535:17)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4543:27)
at http://localhost:9000/bower_components/angular/angular.js:9395:28
at link (http://localhost:9000/bower_components/angular-route/angular-route.js:977:26)
at invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:9039:9) <div ng-view="" class="ng-scope" data-ng-animate="1">(anonymous function) # angular.js:12722(anonymous function) # angular.js:9490invokeLinkFn # angular.js:9041nodeLinkFn # angular.js:8533compositeLinkFn # angular.js:7929publicLinkFn # angular.js:7809boundTranscludeFn # angular.js:7947controllersBoundTransclude # angular.js:8560update # angular-route.js:935Scope.$broadcast # angular.js:16573(anonymous function) # angular-route.js:619processQueue # angular.js:14991(anonymous function) # angular.js:15007Scope.$eval # angular.js:16251Scope.$digest # angular.js:16069Scope.$apply # angular.js:16359done # angular.js:10791completeRequest # angular.js:10989requestLoaded # angular.js:10930
and don't what it means, help needed?
My Code is here
angular.module('pnChatApp')
.controller('MainCtrl', ['$scope', '$rootScope', '$location', 'Pubnub', function ($scope, $rootScope, $location, Pubnub) {
var _ref;
if (!Pubnub.init()) {
$location.path('/join');
}
$scope.controlChannel = '__controlChannel';
$scope.channels = [];
//Publish Chat
$scope.publish = function() {
if (!$scope.selectedChannel) {
return;
}
Pubnub.ngPublish({
channel: $scope.selectedChannel,
message: {
text: $scope.newMessage,
user: $scope.data.username
}
});
return $scope.newMessage = '';
};
//Create Channel
$scope.createChannel = function() {
var channel;
console.log('Creating Channel...');
channel = $scope.newChannel;
$scope.newChannel = '';
Pubnub.ngGrant( {
channel: channel,
read: true,
write: true,
callback: function(){
return console.log(channel + 'All Set', arguments);
}
});
Pubnub.ngGrant( {
channel: channel + '-pnpres',
read: true,
write: false,
callback: function(){
return console.log(channel + 'Presence All Set', arguments);
}
});
Pubnub.ngPublish({
channel: $scope.controlChannel,
message: channel
});
return setTimeout(function() {
$scope.subscribe(channel);
return $scope.showCreate = false;
}, 100);
};
$scope.subscribe = function(channel) {
var _ref;
console.log('Subscribing...');
if (channel === $scope.selectedChannel) {
return;
}
if ($scope.selectedChannel) {
Pubnub.ngUnsubscribe({
channel: $scope.selectedChannel
});
}
$scope.selectedChannel = channel;
$scope.messages = ['Welcome to ' + channel];
Pubnub.ngSubscribe({
channel: $scope.selectedChannel,
state: {
"city": ((_ref = $rootScope.data) !== null ? _ref.city : void 0) || 'unknown'
},
error: function() {
return console.log(arguments);
}
});
$rootScope.$on(Pubnub.ngPrsEv($scope.selectedChannel), function(ngEvent, payload) {
return $scope.$apply(function() {
var newData, userData;
userData = Pubnub.ngPresenceData($scope.selectedChannel);
newData = {};
$scope.users = Pubnub.map(Pubnub.ngListPresence($scope.selectedChannel), function(x) {
var newX;
newX = x;
if (x.replace) {
newX = x.replace(/\w+__/, "");
}
if (x.uuid) {
newX = x.uuid.replace(/\w+__/, "");
}
newData[newX] = userData[x] || {};
return newX;
});
return $scope.userData = newData;
});
});
Pubnub.ngHereNow({
channel: $scope.selectedChannel
});
$rootScope.$on(Pubnub.ngMsgEv($scope.selectedChannel), function(ngEvent, payload) {
var msg;
msg = payload.message.user ? "[" + payload.message.user + "]" + payload.message.text : payload.message.text;
return $scope.$apply(function() {
return $scope.messages.unshift(msg);
});
});
return Pubnub.ngHistory({
channel: $scope.selectedChannel,
auth_key: $scope.authKey,
count: 500
});
};
Pubnub.ngSubscribe({
channel: $scope.controlChannel
});
$rootScope.$on(Pubnub.ngMsgEv($scope.controlChannel), function(ngEvent, payload) {
return $scope.$apply(function() {
if ($scope.channels.indexOf(payload.message) < 0) {
return $scope.channels.push(payload.message);
}
});
});
return Pubnub.ngHistory({
channel: $scope.controlChannel,
count: 500
});
$scope.channels = 'TheWaitingRoom';
return $scope.createChannel();
}]);
The reason for jsonp error is that Pubnub.init has required options argument
Pubnub.init({ publish_key: 'your pub key', subscribe_key: 'your sub key' });
https://github.com/pubnub/pubnub-angular

How to scope correct data in angularfire | firebase | angular | ionic

I'm working on an android game, im using ionic and firebase. I fixed the login: if the user logs in, it checks if the user exists and if not it creates an account.
Now I got a problem scoping the correct data in my controller. I can scope it in html using
{{ user.level }}
I can add data using
users.child($scope.authData.google.cachedUserProfile.id).set({
Username: $scope.authData.google.cachedUserProfile.id
});
i can update data using
user.update({
"level": "Over 9000"
});
But when I try to scope it in my controller it keeps saying undefined or giving me wrong formatted data. (or says user not defined)
var level = user.level;
console.log(level);
my code is
var app = angular.module('starter.controllers', ["firebase"])
//page controller
app.factory("credentials", ["$firebaseAuth",
function($firebaseAuth) {
var FIREB = new Firebase("https://sudokidsapp.firebaseio.com");
return $firebaseAuth(FIREB);
}
]);
app.controller('HomeScreen', function($scope, credentials, $state, $firebaseArray, $firebaseObject) {
credentials.$onAuth(function(authData) {
$scope.authData = authData;
});
$scope.googlelogin = function() {
credentials.$authWithOAuthPopup("google").then(function(authData) {
var users = new Firebase("https://sudokidsapp.firebaseio.com/users");
$scope.users = $firebaseArray(users);
var userId = $scope.authData.google.cachedUserProfile.id;
checkIfUserExists(userId);
function checkIfUserExists(userId) {
var usersRef = new Firebase("https://sudokidsapp.firebaseio.com/users");
usersRef.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}
function userExistsCallback(userId, exists) {
if (exists) {
currentUser = $scope.authData.google.cachedUserProfile.id;
$state.go('app.next');
} else {
$scope.date = JSON.stringify(new Date());
users.child($scope.authData.google.cachedUserProfile.id).set({
Username: $scope.authData.google.cachedUserProfile.id,
Gender: $scope.authData.google.cachedUserProfile.gender || "",
level: 0,
tutorial: true,
world1: true,
world2: false,
world3: false,
world4: false,
world5: false,
stickerset1: true,
stickerset2: false,
stickerset3: false,
stickerset4: false,
stickerset5: false,
character: "none",
date: $scope.date
});
$state.go('app.tutorial');
}
}
}).catch(function(error) {
});
}
});
app.controller("NextControllers", function($scope, $state, credentials, currentUser, $firebaseObject, $firebaseArray) {
var user = currentUser.google.id;
var information = new Firebase("https://sudokidsapp.firebaseio.com/users/" + user);
$scope.information = $firebaseObject(information);
console.log($scope.information);
});
--edit--
Fixed my problem using data snapshot
$scope.UpdateLevel = function(){
information.once("value", function(snapshot) {
var data = snapshot.val();
console.log(data);
console.log(data.level);
console.log(data.world5);
var newdata = data.level + 1 ;
information.update({
"level" : newdata
})
});
}

Titanium with how to run some code when user click on the notification? (Android)

how to run some code when user click on the notification? if user click push notification i want understand coming from push notification.
How can i do?
Thanks
-Gcm Module-
//my gcm module
var gcm = require("nl.vanvianen.android.gcm");
/* If the app is started or resumed act on pending data saved when the notification was received */
var lastData = gcm.getLastData();
if (lastData) {
Ti.API.info("Last notification received " + JSON.stringify(lastData));
gcm.clearLastData();
}
gcm.registerPush({
senderId : 'xxxxxxxx',
notificationSettings : {
sound : 'mysound.mp3',
smallIcon : 'notification_icon.png',
largeIcon : 'appicon.png',
vibrate : true
},
//Push registration success
success : function(event) {
Ti.API.info("Push registration success: " + JSON.stringify(event));
},
//Push registration error
error : function(event) {
Ti.API.info("Push registration error = " + JSON.stringify(event));
alert(event.error);
},
//i want this function Coming from push
data : function(event) {
// console.log(" ******* Coming from push : " + JSON.stringify(event));
},
//my callback funtion call device token
callback : function(event) {
Ti.API.info("Push callback = " + JSON.stringify(event));
var dialog = Ti.UI.createAlertDialog({
title : 'Push received',
message : JSON.stringify(event.data)
// buttonNames: ['View'],
// cancel: 1
});
dialog.addEventListener("click", function(event) {
dialog.hide();
if (event.index == 0) {
/* Do stuff to view the notification */
}
});
dialog.show();
},
});
Titanium.UI.setBackgroundColor('#000');
var win = Ti.UI.createWindow({
backgroundColor : '#ccc',
title : 'Android Cloud Push Notification'
});
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotification = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color : '#000',
height : 53,
width : 200,
top : 100,
});
win.add(submit);
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
loginDefault();
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
});
function loginDefault(e) {
// At first you need to create an user from the application dashboard
// Then login that email and password
Cloud.Users.login({
login : '.....',
password : '....'
}, function(e) {
if (e.success) {
alert("login success");
defaultSubscribe();
} else {
alert('Error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',
device_token : deviceToken,
type : 'android'
}, function(e) {
if (e.success) {
alert('Subscribed for Push Notification!');
} else {
alert('Error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function(evt) {
//alert(evt);
//alert(evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
//alert('Tray Click Launched App (app was not running');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
//alert('Tray Click Focused App (app was already running)');
});
win.open();

some issue about "angularJS work with Plupload

In Directly,I want remove the files in the uploader,I did this
$scope.close = function() {
console.log($scope);
$scope.isOpen = false;
$('.file_container').empty();
**angular.forEach($scope.uploader.files, function(v, k) {
$scope.uploader.removeFile(v);
$scope.fileLength = $scope.uploader.files.length;
});**
};
$scope.uploader = new plupload.Uploader({
runtimes: 'html5,html4',
browse_button: 'addFile',
max_file_size: '20000mb',
chunk_size: '512kb',
// resize: { width: 125, height: 85, quality: 90 },
flash_swf_url: '../scripts/lib/plupload.flash.swf',
filters: [{
extensions: 'jpg,png'
}]
});
$scope.fileLength = 0;
$scope.currentUpload = 0;
$scope.uploader.bind('init', function() {
console.log('init');
});
$scope.uploader.bind('UploadProgress', function(up, files) {
$('.progress_percent').eq($scope.currentUpload).html(files.percent + '%');
$('.progress_bar').eq($scope.currentUpload).css('width', files.percent + '%');
});
$scope.uploader.bind('FilesAdded', function(up, files) {
$scope.$apply(function() {
$scope.fileLength = files.length;
});
console.log($('input[type=file]'));
readURL($('input[type=file]')[0]);
// up.start();
});
$scope.uploader.bind('BeforeUpload', function(up, file) {
var mediaName = 'MediaBank' + Math.random().toString().substr(2);
up.settings.url = '/Upload.ashx?medianame=' + mediaName + '&activityid=2013';
});
$scope.uploader.bind('FileUploaded', function(up, file, info) {
$scope.currentUpload++;
console.log($scope.currentUpload);
});
$scope.uploader.init();
$('#save').bind('click', function() {
$scope.uploader.start();
});
And,when I add 2 files,and when the "$scope.close" function was called,only 1 file was removed...why? thanks all of you !
Might be an issue with the iterator and the fact you are changing the list as you browse it.
You may try to replace :
**angular.forEach($scope.uploader.files, function(v, k) {
$scope.uploader.removeFile(v);
$scope.fileLength = $scope.uploader.files.length;
});**
with :
$scope.uploader.splice(0); // $scope.uploader.splice(); should work too
$scope.fileLength = $scope.uploader.files.length;
Hope this will help

Categories

Resources