Cannot delete element using AngularFire $remove() - angularjs

I am attempting to remove an item (round) from my DB. I can console.log the $id but when I try to roundsList.$remove(round.id) it does not do anything. I am, once again, thoroughly confused...
JS:
.controller('RoundsCtrl', ['$scope', '$firebase', 'FBURL', function ($scope, $firebase, FBURL, url) {
var roundsRef = new Firebase(FBURL + 'rounds');
var roundsList = $firebase(roundsRef).$asArray();
var usersRef = new Firebase(FBURL + 'users');
var usersRef = usersRef.child($scope.loggedInUserID).child('rounds');
var usersRounds = $firebase(usersRef).$asArray();
$scope.removeItem = function (index, round, event) {
// Avoid wrong removing
if (round.$id == undefined) return;
// Firebase: Remove item from the list
$scope.roundsList.$remove(round.$id);
};
/* SET DEFAULT FOR TOGGLE TO COLLAPSED*/
$scope.isCollapsed = true;
/* ONCE ROUNDS ARE LOADED RETURNS ROUNDS BY ID FOR INDIVIDUAL USER*/
usersRounds.$loaded()
.then(function (data) {
$scope.rounds = data.map(function (item) {
console.log(item);
console.log(item.$id);
return roundsList.$getRecord(item.roundID);
});
});}])
HTML:
<tbody ng-repeat="round in rounds | orderBy:orderBy">
<tr>
<td>
{{round.date}}
</td>
<td>
{{round.courseName}}
</td>
<td>
{{round.courseID}}
</td>
<td>
{{round.user}}
</td>
<td>
{{round.userID}}
</td>
<td>
{{round.tags}}
</td>
<td>
View
Edit
<button class="btn btn-danger" ng-click="isCollapsed = !isCollapsed">Delete</button>
</td>
</tr>
<tr collapse="isCollapsed">
<td colspan="7">
<div>
<div class="well well-lg">
<p>Are you sure? This cannot be undone!</p>
<button ng-click="removeItem($index, round, $event)" class="btn btn-danger">Delete Round</button>
<button ng-click="isCollapsed = !isCollapsed" class="btn btn-info">Cancel</button>
</div>
</div>
</td>
</tr>
</tbody>
EDIT:
I was finally able to delete from both DBs using the following code. hope it helps someone else down the line.
/* DELETES ROUND FROM MAIN ROUND DATABASE AND FROM USER SPECIFIC DB*/
var roundsListSync = $firebase(roundsRef);
var usersRoundsListSync = $firebase(usersRefRounds);
$scope.removeItem = function (index, round, event) {
roundsListSync.$remove(round.$id);
//console.log(usersRounds);
var i = 0;
var len = usersRounds.length;
for (; i < len;) {
console.log(usersRounds[i].roundID);
if (usersRounds[i].roundID === round.$id) {
var usersRoundsID = usersRounds[i].$id;
//console.log(usersRoundsID);
usersRoundsListSync.$remove(usersRoundsID);
i++;
} else {
i++;
}
}
};

You are calling $scope.roundsList.$remove(round.$id), however you have not declared roundsList in the scope: var roundsList = $firebase(roundsRef).$asArray(); Try var roundsList = $firebase(roundsRef).$asArray() instead.
If that doesn't work, try to make a firebase reference that is not an array:
var roundsListSync = $firebase(roundsRef);
roundsListSync.$remove(round.$id);

Related

Automatically added ng-hide in a button

<table>
<tr ng-repeat="response in customUserResponse">
<td>
<div class="buttons" align="center">
<button ng-disabled="isReadOnly" class="btn actionBtn edit-disable"
ng-click="editResponse($index)"><i class="fa fa-edit"></i></button>
<button ng-show="!response.Is_Global__c"
ng-model="response.Is_Global__c" ng-
disabled="isReadOnly" class="btn actionBtn edit-disable"
ng-click="deleteQuestion($index)">
<i class="fa fa-trash"></i></button>
</div>
</td>
</tr>
</table>
<table class="table" style="margin-top: 10px;">
<tr>
<td>
<button ng-disabled="isReadOnly" class="btn actionBtn"
ng-click="addUserRow()">
<i class="fa fa-plus"></i></button>
</td>
</tr>
</table>
$scope.addUserRow = function () {
var l = $scope.customUserResponse.length;
if(l==0)
{
l = $scope.customUserQuestion.length;
}
var quest = {Question_Text__c:"", Response_Value__c:"", Status__c:"", Comments__c:"",
Is_Global__c:"false", Order__c:l};
$scope.enabledEditResponse[l] = true;
$scope.customUserResponse.push(quest);
//var element = document.getElementByClass("deleteButton");
//element.classList.remove("ng-hide");
//angular.element(document.querySelector("#deleteButton")).removeClass("ng-hide");
//$scope.showDeleteBtn = true;
//$scope.$apply();
};
$scope.submitQuestion = function() {
var data = [];
if($scope.customUserResponse.length >= $scope.customUserQuestion.length)
data = data.concat($scope.customUserResponse);
else {
data = data.concat($scope.customUserQuestion);
data = data.concat($scope.customUserResponse);
}
data.forEach(function(element) { element.Application_Id__c = $scope.appId; });
var len = data.length;
for(var i=0; i<len;i++){
data[i].Order__c = i+1;
}
ApplicationDataSource.saveFundingChecklistResponse(angular.toJson(data), function (result) {
if(result[0] !='{\"error\": true, \"result\": null}')
{
$scope.getResponse($scope.loadResponseInTable);
alert('Data saved Successfully');
$scope.resetEnabledEditResponse();
//$scope.init();
}
else
{
alert('Something went wrong. Data is not saved.');
}
$scope.$apply();
});
};
When response.Is_Global__c == false, the delete button will show.
When I clicked plus button one row is added but the delete button doesn't show. But after saving both button shows. When I inspect the code, I see ng-hide is automatically added in the class and if I remove manually the ng-hide class then the button shows.
ng-hide class is added when ng-show expression evaluates to a falsy value:
This means that after the save action this expression becomes false:
!response.Is_Global__c
The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element.
https://docs.angularjs.org/api/ng/directive/ngShow

Push empty row with input field using angularjs

I have one table which have edit, delete and add options. My problem is when I click on add button want to add row with empty input fields. I have write below code for this. What should I do to add empty row with empty input values.
My code
<div ng-controller="AppKeysCtrl">
<button ng-click="add()">
Add
</button>
<table class="table table-hover mytable">
<thead>
<tr>
<th></th>
<th>Created</th>
<th>App Key</th>
<th>Name</th>
<th>Level</th>
http://jsfiddle.net/Thw8n/155/#update <th>Active</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="entry in appkeys" data-ng-class="{danger:!entry.active}">
<td>{{$index + 1}}</td>
<td>{{entry.timestamp | date:'mediumDate'}}</td>
<td>{{entry.appkey}}</td>
<td>
<span data-ng-hide="editMode">{{entry.name}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="entry.name" data-ng-required />
</td>
<td>
<span data-ng-hide="editMode">{{entry.level}}</span>
<select class="form-control" name="entry.level" data-ng-model="entry.level" data-ng-show="editMode">
<option value="3">3 - Developer Access - [Temporary]</option>
<option value="2">2 - Standard Tool Access - [Default]</option>
<option value="1">1 - Administrative Access - [Admin Section Only]</option>
</select>
</td>
<td>
<span data-ng-hide="editMode">{{entry.active && 'Active' || 'Inactive'}}</span>
<select class="form-control" name="entry.active" data-ng-model="entry.active" data-ng-show="editMode">
<option value="true">Active</option>
<option value="false">Inactive</option>
</select>
</td>
<td>
<button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false" class="btn btn-default">Save</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; cancel($index)" class="btn btn-default">Cancel</button>
</td>
</tr>
</tbody>
</table>
<pre>newField: {{newField|json}}</pre></br></br>
<pre>appkeys: {{appkeys|json}}</pre>
</div>
app = angular.module("formDemo", []);
function AppKeysCtrl($scope, $http, $location) {
var tmpDate = new Date();
$scope.newField = [];
$scope.editing = false;
$scope.appkeys = [
{ "appkey" : "0123456789", "name" : "My new app key", "created" : tmpDate },
{ "appkey" : "abcdefghij", "name" : "Someone elses app key", "created" : tmpDate }
];
$scope.editAppKey = function(field) {
$scope.editing = $scope.appkeys.indexOf(field);
$scope.newField[$scope.editing] = angular.copy(field);
}
$scope.saveField = function(index) {
//if ($scope.editing !== false) {
$scope.appkeys[$scope.editing] = $scope.newField;
//$scope.editing = false;
//}
};
$scope.cancel = function(index) {
//if ($scope.editing !== false) {
$scope.appkeys[index] = $scope.newField[index];
$scope.editing = false;
//}
};
$scope.add = function () {
var entry = {};
//$scope.goals.push(goal);
$scope.appkeys.push(entry);
};
}
angular.element(document).ready(function() {
angular.bootstrap(document, ["formDemo"]);
});
I have problem in this that when I click on add empty row is adding which have form fields with ng-hide attribute. I want to add row dynamically with new input boxes for each column. What should I do for this? Please help.
It's quite simple. You need to push an object with blank value into your array.
Below is the code:
Controller
$scope.add = function () {
$scope.appkeys.push({appkey : '', name : '', created : '' });
};
The above code will only add a row. I have updated your JSFiddle for your desired output.
Please go through with the given link.
http://jsfiddle.net/Thw8n/570/
You need to paste the following code:
$scope.add = function () {
$scope.appkeys.push({appkey : '', name : '', created : '' });
};
You can push object with empty properties in your appkey array:
var tempObject = {
"appkey":"",
"name":"",
"created":""
};
$scope.appkeys.push(tempObject);

Issues converting "controller as" syntax to classic $scope

I have had major issues trying to convert my code from "controller as/this" syntax to classic $scope syntax, without breaking the code. I tried simply replacing "this" with $scope and removing the "controller as" assignments for both controllers, with no luck. I have created a jsfiddle for this with the controller as/this syntax so you can see how it should be working correctly prior to converting the syntax to $scope. https://jsfiddle.net/6zk9vujo/6/
This is another jsfiffle showing the broken code, when I simply replace _this with $scope and remove the controller as assignments in the html https://jsfiddle.net/6zk9vujo/12/ Thank you for your help in advance.
HTML
<div ng-app="app">
<div ng-controller="mainController as main">
<h2>
Main Controller
</h2>
<div>
<table>
<tr>
<td>Item</td>
<td>Price</td>
<td>Quantity</td>
<td></td>
</tr>
<tr ng-repeat="product in main.items">
<td>{{product.name}}</td>
<td>{{product.price | currency}}</td>
<td>
<button ng-click="main.increaseItemAmount(product)">
+
</button>
{{product.quantity}}
<button ng-click="main.decreaseItemAmount(product)">
-
</button>
<button ng-click="main.addToCart(product)">
Add to Cart
</button>
</td>
</tr>
</table>
</div>
</div>
<div ng-controller="cartController as cart">
<h2>
Cart Controller
</h2>
<div>
<table>
<tr>
<td>Item</td>
<td>Price</td>
<td>Quantity</td>
<td></td>
</tr>
<tr ng-repeat="product in cart.cartStorage.items">
<td>{{product.name}}</td>
<td>{{product.price | currency}}</td>
<td>
<button ng-click="cart.increaseItemAmount(product)">
+
</button>
{{product.quantity}}
<button ng-click="cart.decreaseItemAmount(product)">
-
</button>
<button ng-click="cart.removeFromCart(product)">
Remove from Cart
</button>
</td>
</tr>
</table>
</div>
</div>
</div>
JAVASCRIPT
angular.module('app', [])
.factory('cartStorage', function() {
var _cart = {
items: []
};
var service = {
get cartItems() {
return _cart;
}
}
return service;
})
.controller('mainController', function(cartStorage) {
var _this = this;
_this.cartStorage = cartStorage.cartItems;
_this.items = [{
name: 'Apple',
price: 2.5,
quantity: 1
}];
_this.addToCart = function(product) {
_this.cartStorage.items.push(product);
product.addedToCart = true;
}
_this.increaseItemAmount = function(product) {
product.quantity++;
product.showAddToCart = true;
}
_this.decreaseItemAmount = function(item) {
product.quantity--;
if (product.quantity <= 0) {
product.quantity = 0;
product.addedToCart = false;
product.showAddToCart = false;
var itemIndex = _this.cartStorage.items.indexOf(product);
if (productIndex > -1) {
_this.cartStorage.items.splice(productIndex, 1);
}
} else {
product.showAddToCart = true;
}
}
})
.controller('cartController', function(cartStorage) {
var _this = this;
_this.cartStorage = cartStorage.cartItems;
_this.increaseItemAmount = function(item) {
product.quantity++;
}
_this.decreaseItemAmount = function(item) {
item.quantity--;
if (item.quantity <= 0) {
item.quantity = 0;
item.addedToCart = false;
item.showAddToCart = false;
var productIndex = _this.cartStorage.items.indexOf(item);
if (productIndex > -1) {
_this.cartStorage.items.splice(productIndex, 1);
}
}
}
_this.removeFromCart = function(item) {
item.quantity = 0;
item.addedToCart = false;
item.showAddToCart = false;
var productIndex = _this.cartStorage.items.productOf(item);
if (productIndex > -1) {
_this.cartStorage.items.splice(productIndex, 1);
}
}
});
In the template, remove all main. and cart. and change to ng-controller="mainController" and ng-controller="cartController".
In your controllers, inject $scope and assign it to _this for easiest migration.
.controller('mainController', function($scope, cartStorage) {
var _this = $scope;
and
.controller('cartController', function($scope, cartStorage) {
var _this = $scope;
https://jsfiddle.net/6zk9vujo/10/
Alternatively, just replace all _this references with $scope in your controllers.
You also have a bunch of mixed up product / item and productIndex / itemIndex variables. I've standardised them all in this fiddle as well as fixed the logic around re-adding the same product.
https://jsfiddle.net/6zk9vujo/13/
It will work if you remove the "as" syntax when you define the controller in the view: ng-controller="mainController" and ng-controller="cartController".
Edited: I made a mistake of putting the wrong fiddle link.
https://jsfiddle.net/analiza641/jr0stbLq/3/

AngularJS - Not update table-pagination after http-get success's event

i have a problem. I'm using AngularJs with WebService-Rest, and can't update some table after the call HTTP-GET to WebService. I did tested everything but i can't get it.
Next, i attach the code. Thanks!
HTML:
...
<div class="row" ng-app="SIGA" ng-controller="CreateTable">
<div class="container-fluid">
<table class="table table-striped">
<tbody>
<tr>
<td>Buscar</td>
<td><input type="text" ng-model="search.nombre" /></td>
</tr>
<tr ng-repeat="e in estaciones | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Detalle
</button>
</td>
<td>{{e.nombre}}</td>
</tr>
</tbody>
</table>
<pagination total-items="totalItems" ng-model="currentPage"
max-size="5" boundary-links="true"
items-per-page="numPerPage" class="pagination-sm">
</pagination>
</div>
</div>
...
JS: ...
app.controller('RestEstacion', function ($rootScope, $http) {
$http.get('http://localhost:8080/sigarest/webresources/entity.estaciones').
success(function(data) {
$rootScope.estaciones = data; UpdateTable($rootScope);
}).
error(function(status) {
alert('error:'+status);
});
});
app.controller('CreateTable', function ($scope,$rootScope) {
$rootScope.predicate = 'nombre';
$rootScope.reverse = true;
$rootScope.currentPage = 1;
$rootScope.order = function (predicate) {
$rootScope.reverse = ($rootScope.predicate === predicate) ? !$rootScope.reverse : false;
$rootScope.predicate = predicate;
};
$rootScope.estaciones = [];
$rootScope.totalItems = $rootScope.estaciones.length;
$rootScope.numPerPage = 5;
$rootScope.paginate = function (value) {
var begin, end, index;
begin = ($rootScope.currentPage - 1) * $rootScope.numPerPage;
end = begin + $rootScope.numPerPage;
index = $rootScope.estaciones.indexOf(value);
return (begin <= index && index < end);
};
});
JS (Update Function):
function UpdateTable($rootScope){
$rootScope.totalItems = $rootScope.estaciones.length;}
** Original Answer (what comments refer to) **
I think you are assigning the get response object rather than the data inside it. Try this:
success(function(response) {
$rootScope.estaciones = response.data;
UpdateTable($rootScope);
}).
** EDIT **
Now that we have established that you are returning data from the API, the real issue appears to be the double controller using $rootScope as a bridge, which can work but is a bit of an anti-pattern in Angular.
The first controller in your app is trying to act like a service, and so really needs to be converted into one. Here is some SAMPLE PSUEDO CODE to give the idea. I do not fully understand your code, like the pagination directive. There should be a click handler in the pagination directive that would call the service method changePagination and pass in the new page number. There should be no need for $rootScope anywhere in this.
JS
app.service('RestEstacionService', function ($http) {
var RestEstacionService = this;
this.apiData = null;
this.tableData = null;
this.currentPage = 1;
this.numPerPage = 5;
this.url = 'http://localhost:8080/sigarest/webresources/entity.estaciones';
this.getData = function (url) {
return $http.get(url).then(function(response) {
RestEstacionService.apiData = response.data;
// do success stuff here
// figure out which page the view should display
// assign a portion of the api data to the tableData variable
})
};
this.changePagination = function (newPage) {
// do your your pagination work here
};
});
app.controller('RestEstacionController', ['$scope', 'RestEstacionService', function ($scope, RestEstacionService) {
$scope.service = RestEstacionService;
RestEstacionService.getData(RestEstacionService.url);
}]);
HTML
<div class="row" ng-app="SIGA" ng-controller="RestEstacionController">
<div class="container-fluid">
<table class="table table-striped">
<tbody>
<tr>
<td>Buscar</td>
<td><input type="text" ng-model="search.nombre" /></td>
</tr>
<tr ng-repeat="row in services.tableData | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Detalle
</button>
</td>
<td>{{row.nombre}}</td>
</tr>
</tbody>
</table>
<pagination total-items="services.apiData.length" ng-model="services.currentPage"
max-size="5" boundary-links="true"
items-per-page="services.numPerPage" class="pagination-sm">
</pagination>
</div>

Passing base64 string to object's attribute in AngularJS

I'm trying to upload an image via an input field, tie the base64 of the image to a variable, then add that variable to the attribute of an object so I can store it in my Firebase db.
Input form & field for object:
<div class="row modalDetail">
<h3>New Episode</h3>
<table class="">
<tbody>
<tr>
<td class="labelField">Name</td>
<td><input type='text' ng-model='episode.name'></td>
</tr>
<tr>
<td class="labelField">Title</td>
<td><input type='text' ng-model='episode.title'></td>
</tr>
<tr>
<td class="labelField">Description</td>
<td><input type='text' ng-model='episode.shortDescription'></td>
</tr>
<tr>
<td class="labelField">Time</td>
<td><input type='text' ng-model='episode.time'></td>
</tr>
</tbody>
</table>
<img src="../images/placeholder.png" id="pano">
<!-- START Image File Upload -->
<td class="labelField">Image</td>
<span class="btn btn-default btn-file">
<input type="file" accept="image/*" capture="camera" id="file-upload">
</span>
<div id="spin"></div>
<div class='btn btn-warning' ng-click='createEpisode()'> Create an Episode</div>
</div>
The service for uploading to Firebase:
'use strict';
app.service('Uploader', ['$firebase', 'FIREBASE_TEST_URL', function($firebase, FIREBASE_TEST_URL) {
var ref = new Firebase(FIREBASE_TEST_URL);
var episodes = $firebase(ref);
return {
all: episodes,
create: function(episode) {
location.reload();
//Add to firebase db
return episodes.$add(episode);
},
delete: function(episodeId) {
location.reload();
return episodes.$remove(episodeId);
},
update: function(episode) {
location.reload();
return episodes.$save(episode);
}
};
}]);
Controller that has the file handling for the image, etc.:
'use strict';
app.controller('UploadCtrl', ['$scope', 'Uploader', function ($scope, Uploader) {
$scope.episodes = Uploader.all;
$scope.createEpisode = function(){
Uploader.create($scope.episode).then(function(data){
$scope.episode.name = '';
$scope.episode.title = '';
$scope.episode.description = '';
$scope.episode.time = '';
$scope.episode.img1 = $scope.episodeImgData;
});
};
$scope.deleteEpisode = function(episodeId){
bootbox.confirm('Are you sure you want to delete this episode?', function(result) {
if (result === true) {
Uploader.delete(episodeId).then(function(data){
console.log('Episode successfully deleted!');
});
}
});
};
$scope.updateEpisode = function(episode) {
Uploader.update($scope.episode).then(function(data) {
console.log(episode);
console.log('Episode successfully updated.');
});
};
$scope.selectEpisode = function(object) {
$scope.selectedEpisode = object;
setTimeout(function(){ $scope.$apply($scope.selectedEpisode = object); });
};
// ********************************************************************************** //
// START Image Upload: https://github.com/firebase/firepano/blob/gh-pages/firepano.js //
// REQUIRED: app/scripts/js/crypto.js in index.js
var spinner = new Spinner({color: '#ddd'});
$scope.episodeImgData = '../images/defaultplaceholder.png';
function handleFileSelectAdd(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
$scope.episodeImgData = e.target.result;
document.getElementById('pano').src = $scope.episodeImgData;
console.log($scope.episodeImgData);
};
})(f);
reader.readAsDataURL(f);
}
function handleFileSelectEdit(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
$scpope.episodeImgData = e.target.result;
document.getElementById('pano2').src = $scope.episodeImgData;
$scope.selectedEpisode.img1 = $scope.episodeImgData;
console.log($scope.episodeImgData);
};
})(f);
reader.readAsDataURL(f);
}
$(function() {
$('#spin').append(spinner);
document.getElementById('file-upload').addEventListener('change', handleFileSelectAdd, false);
document.getElementById('file-upload2').addEventListener('change', handleFileSelectEdit, false);
});
// END Image Upload: https://github.com/firebase/firepano/blob/gh-pages/firepano.js //
// ******************************************************************************** //
}]);
All the attributes in the form save to the DB except img1. When the update button is clicked, I thought I could just pass in episodeImgData to the object (img1 variable) to save, but it doesn't save anything at all (just the form variables tied to episode.name, etc.). What's the best way to do this? I'm using parts of the FirePano example (https://github.com/firebase/firepano/blob/gh-pages/firepano.js) for the image handling.
Update (20160519): Firebase just released a new feature called Firebase Storage. This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.
There were a lot of small problems with that code.
Since your episodes are an array, you can to create is with $asArray, otherwise it won't have a $add method: var episodes = $firebase(ref).$asArray();
You were calling location.reload() before sending the data to the server
Your file-upload handler wasn't triggering for me
There were dangling references to the spinner from firepano
I think that first two were the biggest. But it is hard to find that type of problem if you don't provide a minimal example that reproduces the problem. I did that for you now.
In the end, the code is not too big so I'll share it here:
var app = angular.module('myapp', ['firebase'])
.service('Uploader', function($firebase) {
var ref = new Firebase('http://<yourfirebase>.firebaseio.com/');
var episodes = $firebase(ref).$asArray();
return {
all: episodes,
create: function(episode) {
//Add to firebase db
return episodes.$add(episode);
}
};
})
.controller('UploadCtrl', function ($scope, Uploader) {
$scope.episodes = Uploader.all;
$scope.createEpisode = function() {
if ($scope.episodeImgData) {
$scope.episode.img1 = $scope.episodeImgData;
}
Uploader.create($scope.episode);
};
$scope.handleFileSelectAdd = function(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
$scope.episodeImgData = e.target.result;
document.getElementById('pano').src = $scope.episodeImgData;
};
})(f);
reader.readAsDataURL(f);
};
document.getElementById('file-upload').addEventListener('change', $scope.handleFileSelectAdd, false);
});
The corresponding (body) HTML:
<body ng-app='myapp'>
<div class="row modalDetail" ng-controller='UploadCtrl'>
<h3>New Episode</h3>
<table class="" ng-model='episode'>
<tbody>
<tr>
<td class="labelField">Name</td>
<td><input type='text' ng-model='episode.name'></td>
</tr>
<tr>
<td class="labelField">Title</td>
<td><input type='text' ng-model='episode.title'></td>
</tr>
<tr>
<td class="labelField">Description</td>
<td><input type='text' ng-model='episode.shortDescription'></td>
</tr>
<tr>
<td class="labelField">Time</td>
<td><input type='text' ng-model='episode.time'></td>
</tr>
</tbody>
</table>
<td class="labelField">Image</td>
<span class="btn btn-default btn-file">
<input type="file" accept="image/*" capture="camera" id="file-upload">
</span>
<div class='btn btn-warning' ng-click='createEpisode()'>Create an Episode</div>
<br/>
<img id="pano">
</div>
</body>
This is a working demo if creating an episode with optional image data: http://jsbin.com/roriwu/7.

Resources