How to read file zip using JSZip in Firefox SDK - firefox-addon

I want to make addons to work to extract the zip file locally like this (here). But I have a problem when making use firefox SDK. Which can not be read zip because somethings wrong when get path of fileinput and errors unsupported format because dataType not ArrayBuffer.
HTML
<input type="file" name="file" id="import" class="hide" />
myscript.js
var fileInput = document.getElementById('import');
fileInput.addEventListener('change', function(e) {
var zipFileToLoad = fileInput.files[0];
var tampJson = [];
JSZip.loadAsync(zipFileToLoad)
.then(function(zip) {
console.dir(zip);
zip.forEach(function (relativePath, zipEntry) {
if(zipEntry.dosPermissions == null){
alert('Permissions trouble !')
}
if(typeof(zipEntry['_data']['compressedContent']) != 'undefined'){
//var text = String.fromCharCode.apply(null, new Uint8Array(zipEntry['_data']['compressedContent']));
var text = new TextDecoder("utf-8").decode(zipEntry['_data']['compressedContent']);
var dec = text.toString();
var json = JSON.parse(dec);
if(json != null){
var keys = ['name', 'description', 'data', 'created_at', 'updated_at'];
keys.forEach(function(key){
if (key in json){
if(key == keys[keys.length - 1]){
tampJson.push(json);
}
}else{
dialog({
title: "Warning",
description: "<b>Wrong format, </b> are you sure to continue?",
yesButton: "yes",
cancelButton: "No",
yesCallback: function() {
$(this).closest('.overlay').removeClass("active");
},
cancelCallback: function() {
$(this).closest('.overlay').removeClass("active");
return false;
}
});
}
});
}else{
alert('format parse gagal');
}
}
});
if(tampJson.length > 0){
saveByImport(tampJson, 0);
}else{
alert('Oops file empty');
}
}, function (e) {
alert('Oops import fail '+ e);
});
Can't error in console. I just can not ArrayBuffer from fileinput.
This script can work in chrome extension but not work in firefox sdk.
So please help me for solving this problem.

I used an older version of jszip in my addon here. You can use the jszip from my repository and use it the way I did. See here - https://github.com/Noitidart/Chrome-Store-Foxified/blob/master/resources/scripts/MainWorker.js#L195

Related

Quasar File Picker doesn't upload image in ios

I want to implement image uploading. It works for web (Chrome/Safari), but not for mobile ios (built with Capacitor). It shows image selection, but when I select it nothing happens.
Here is my input:
<q-file
v-model="avatarFile"
accept=".jpg, .png"
#input="uploadImage"
/>
async uploadImage() {
if (this.avatarFile) {
let extension = "jpg";
if (this.avatarFile.type === "image/png") {
extension = "png";
}
try {
this.loading = 1;
const {
data: {
uploadUrl: { uploadUrl },
},
} = await this.$apollo.query({
query: GET_UPLOAD_URL,
variables: {
extension,
},
});
await axios.put(uploadUrl, this.avatarFile);
await setTimeout(() => {
this.$emit("on-image-upload");
this.loading = 0;
}, 3000);
} catch (e) {
this.alertError(e);
this.loading = 0;
}
}
}
What am I doing wrong? Thanx in advance!
Found the solution. My accept rule had the wrong format. This works:
accept="image/*"

Google sheet script submit specific value

I'm trying to send form details to a google sheets script working. Currently the following code submits a form field to a google sheet perfectly.
var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'timestamp' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
But I'm trying to only submit a specific field value, and if submitted, only once. So it would error if it existed in the google sheet. I can't figure it out.
Here is the JS
const scriptURL = 'HIDDEN'
const form = document.forms['submit-to-google-sheet']
const loading = document.querySelector('.js-loading')
const successMessage = document.querySelector('.js-success-message')
const errorMessage = document.querySelector('.js-error-message')
form.addEventListener('submit', e => {
e.preventDefault()
showLoadingIndicator()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => showSuccessMessage(response))
.catch(error => showErrorMessage(error))
})
function showLoadingIndicator () {
form.classList.add('is-hidden')
loading.classList.remove('is-hidden')
}
function showSuccessMessage (response) {
console.log('Submitted', response)
setTimeout(() => {
successMessage.classList.remove('is-hidden')
loading.classList.add('is-hidden')
}, 500)
}
function showErrorMessage (error) {
console.error('Error!', error.message)
setTimeout(() => {
errorMessage.classList.remove('is-hidden')
loading.classList.add('is-hidden')
}, 500)
}
Here is the HTML
<div class="form-container">
<form name="submit-to-google-sheet">
<input name="code" type="text" placeholder="Enter Code" required>
<button type="submit">Submit</button>
</form>
<div class="loading js-loading is-hidden">
<div class="loading-spinner">
<svg><circle cx="25" cy="25" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg>
</div>
</div>
<p class="js-success-message is-hidden">You're not a winner, better luck next time.</p>
<p class="js-error-message is-hidden">Error: Something wen't wrong, please try again later.</p>
</div>
Assuming you want to check for duplicates for the content of newRow[1] in column 2:
Retrieve the values from column B and convert them into a 1D array with flat()
Verify with indexOf() either the content of newRow is already contained in column B (indexOf() will return -1 if a value is not contained in an array)
A sample where newRow[1] was manually set to 123 for testing purposes:
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'timestamp' ? new Date() : e.parameter[header]
})
newRow[1] = 123;
var columnTwo = sheet.getRange(1,2, sheet.getLastRow(), 1).getValues().flat();
if (columnTwo.indexOf(newRow[1]) == - 1){
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
UPDATE
indexOf() only works correctly for values of the same content AND data type.
If your spreadsheet values are numbers, but the incoming posted value is recognized string, you need to convert it to a number for correct comparison. This can be done by comparing with
if (columnTwo.indexOf(Number(newRow[1])) == - 1){...

Square Payment Form Request Card Nonce not working in versions of safari

I seem to be having an issue with the requestCardNonce() function for some safari users This is using the Javascript API in my .net MVC application.
The current version I'm testing on appears to be working (13.0.4) but users are still reporting an inability to complete their orders with previous versions of safari. When filling in their information they're able to see the dialog that contains the fields for the Card Name, Number, CVV, and Postal code and expiration date but can't seem to proceed to the next dialog. The onGetCardNonce(event) function seems to be having issues executing properly.
The code I have currently looked like this
if (gateway == "Square Payment Gateway") {
paymentForm = new SqPaymentForm({
applicationId: appId,
inputClass: 'sq-input',
autoBuild: false,
cardNumber: {
elementId: 'sq-card-number',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal'
},
// SqPaymentForm callback functions
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData) {
let errMsg = "";
if (errors) {
// Log errors from nonce generation to the browser developer console.
console.error('Encountered errors:');
errors.forEach(function (error) {
console.error(' ' + error.message);
errMsg += ' ' + error.message;
});
alert('Encountered errors' + errMsg);
return;
}
$("#CardNumber").val(cardData["last_4"]);
$("#squareToken").val(nonce)
$("#form-container").dialog("close");
var isValid = true;
$('#CardName,#CardNumber').each(function () {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "",
"background": ""
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if ($("#Total").val() == "0.00" || $("#Total").val() == "0")
isValid = true;
if (isValid == false) {
$('#PayCreditCard')[0].disabled = false;
}
else {
var targetUrl = $(this).attr("href");
// Open Terms & Conditions
$("#dvTermsConditions").dialog("open");
$("#dvTermsConditions").dialog({
autoOpen: false,
modal: true,
buttons: {
"Proceed": function () {
if ($('#AgreeToTerms').is(':checked')) {
$(':input[type="submit"]').prop('disabled', true);
$(this).dialog("close");
$("#frmCheckOut").submit();
}
else {
alert("You must agree to the terms & conditions.");
}
},
"Cancel": function () {
$('#PayCreditCard')[0].disabled = false;
$(this).dialog("close");
}
}
});
}
}
}
});
paymentForm.build();
function onGetCardNonce(event) {
// Don't submit the form until SqPaymentForm returns with a nonce
event.preventDefault();
// Request a nonce from the SqPaymentForm object
paymentForm.requestCardNonce();
}
function closeCC() {
$("#form-container").dialog("close");
}
}
Originally the issue was that payment form was not found so I moved the definition of that outside the if statement and that seemed to clear up the issue for safari 13.0.4+
Does anyone have suggestions on how to make the square payment form (v2) work on all (or at least the last 3+ years) of versions of Safari (not on mobile)?

Difficulty with upload csv to knockout js table (ASP MVC)

I've been working with these two tutorials, but am having difficulty merging them together to get an upload csv to populate the table. It most likely is my lack of understanding of the view model.
Here's the tutorial for the knockout js editable table from the knockout js site: KnockoutJS: Editable Grid Table
And here's the tutorial for uploading a csv I'm referencing:
KnockoutJS - Upload CSV
Here's the javascript code I've been working on to upload a csv to my table. I keep getting "JavaScript runtime error: Unable to get property 'push' of undefined or null reference" - I marked in comments the problem spot. As you can see, I'm having trouble with the view model.
<script>
var UserModel = function (users) {
var self = this;
self.users = ko.observableArray(users);
self.addUser = function () {
self.users.push({
id: "",
firstName: "",
lastName: ""
});
};
self.removeUser = function (user) {
self.users.remove(user);
};
self.save = function (form) {
sendData = ko.toJSON(self.users);
$.ajax({
url: '/Users/CreateMultiple',
contentType: 'application/json',
async: true,
type: 'POST',
dataType: 'json',
data: sendData,
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS");
}
});
};
};
var viewModel = new UserModel([
{ id: "", firstName: "", lastName: "" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
/////
/////Upload CSV
/////
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
reader.onload = Load_CSVData;
reader.readAsText(FileToRead.files.item(0));
}
});
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
UserModel.users.push(new UserModel()//here's my problem
.id(csvID)
.firstName(csvFirstName)
.lastName(csvLastName)
)
});
}
</script>
I was able to identify the fully qualified for the observable array which in turn made it work:
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
viewModel.users.push({
id: csvID,
firstName: csvFirstName,
lastName: csvLastName
});
}

showing document type alias or name of selected node in Multi node tree picker inside content tab in Umbraco V7

I'm looking for a way to show document type alias or name of selected content in Multinode tree picker inside content tab.
This will tremendously help me to quickly identify type of content attached. Also hovering a content added in MNTP inside content shows numeric path which is not quite useful, is there a way to show path names instead of id's?
Attaching image for reference.
Kindly suggest.
The easiest way to do this is to simply modify the MNTP property editor and have it show the extra data. It is however not really recommended to modify these files since it will be reverted every time you upgrade your Umbraco site.
There is a bit of a hacky workaround to achieve what you want however;
Angular has something called interceptors, allowing you to intercept and modify requests being made. By registrering an interceptor you could intercept the requests to contentpicker.html and redirect it to a contentpicker.html file located somewhere else - this means you will be able to just copy this file somewhere else and not modify the one in the umbraco folder being overwritten by upgrades.
Unfortunately in this case it isn't enough to just override the view being sent to the browser, since the document type alias is not actually available to that view - so the view would never be able to show the alias even if we modified it.
To work around that, you could create a copy of the contentpicker.controller.js file and create a modified version of that to use in your custom contentpicker.html view. This modified ContentPickerController would make sure to include the contentTypeAlias in the model being used in rendering the view.
All of this can be wrapped up as a "package" in the App_Plugins folder and it will be nicely separated away from being overwritten when you upgrade Umbraco, while being automatically loaded via the package.manifest file. The only caveat is that in case something is updated in the content picker code, you would have to manually merge those updates over into your custom content picker files - fortunately the content picker is rarely updated.
Place the following files in App_Plugins/CustomContentPicker/ folder and you should have what you want without actually modifying the core code:
package.manifest
{
"javascript": [
"~/App_Plugins/CustomContentPicker/customcontentpicker.controller.js"
]
}
customcontentpicker.html
<div ng-controller="Umbraco.PropertyEditors.CustomContentPickerController" class="umb-editor umb-contentpicker">
<ng-form name="contentPickerForm">
<ul class="unstyled list-icons"
ui-sortable
ng-model="renderModel">
<li ng-repeat="node in renderModel" ng-attr-title="{{model.config.showPathOnHover && 'Path: ' + node.path || undefined}}">
<i class="icon icon-navigation handle"></i>
<a href="#" prevent-default ng-click="remove($index)">
<i class="icon icon-delete red hover-show"></i>
<i class="{{node.icon}} hover-hide"></i>
{{node.name}}<br />
({{node.contentTypeAlias}})
</a>
<div ng-if="!dialogEditor && ((model.config.showOpenButton && allowOpenButton) || (model.config.showEditButton && allowEditButton))">
<small ng-if="model.config.showOpenButton && allowOpenButton"><a href ng-click="showNode($index)"><localize key="open">Open</localize></a></small>
<small ng-if="model.config.showEditButton && allowEditButton"><a href umb-launch-mini-editor="node"><localize key="edit">Edit</localize></a></small>
</div>
</li>
</ul>
<ul class="unstyled list-icons" ng-show="model.config.multiPicker === true || renderModel.length === 0">
<li>
<i class="icon icon-add blue"></i>
<a href="#" ng-click="openContentPicker()" prevent-default>
<localize key="general_add">Add</localize>
</a>
</li>
</ul>
<!--These are here because we need ng-form fields to validate against-->
<input type="hidden" name="minCount" ng-model="renderModel" />
<input type="hidden" name="maxCount" ng-model="renderModel" />
<div class="help-inline" val-msg-for="minCount" val-toggle-msg="minCount">
You need to add at least {{model.config.minNumber}} items
</div>
<div class="help-inline" val-msg-for="maxCount" val-toggle-msg="maxCount">
You can only have {{model.config.maxNumber}} items selected
</div>
</ng-form>
<umb-overlay
ng-if="contentPickerOverlay.show"
model="contentPickerOverlay"
view="contentPickerOverlay.view"
position="right">
</umb-overlay>
</div>
customcontentpicker.controller.js
angular.module('umbraco.services').config([
'$httpProvider',
function ($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (request) {
var url = 'views/propertyeditors/contentpicker/contentpicker.html';
if (request.url.indexOf(url) !== -1) {
request.url = request.url.replace(url, '/App_Plugins/CustomContentPicker/customcontentpicker.html');
}
return request || $q.when(request);
}
};
});
}]);
// Below is contentpicker.controller.js modified
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
function customContentPickerController($scope, dialogService, entityResource, editorState, $log, iconHelper, $routeParams, fileManager, contentEditingHelper, angularHelper, navigationService, $location) {
function trim(str, chr) {
var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g');
return str.replace(rgxtrim, '');
}
function startWatch() {
//We need to watch our renderModel so that we can update the underlying $scope.model.value properly, this is required
// because the ui-sortable doesn't dispatch an event after the digest of the sort operation. Any of the events for UI sortable
// occur after the DOM has updated but BEFORE the digest has occured so the model has NOT changed yet - it even states so in the docs.
// In their source code there is no event so we need to just subscribe to our model changes here.
//This also makes it easier to manage models, we update one and the rest will just work.
$scope.$watch(function () {
//return the joined Ids as a string to watch
return _.map($scope.renderModel, function (i) {
return i.id;
}).join();
}, function (newVal) {
var currIds = _.map($scope.renderModel, function (i) {
return i.id;
});
$scope.model.value = trim(currIds.join(), ",");
//Validate!
if ($scope.model.config && $scope.model.config.minNumber && parseInt($scope.model.config.minNumber) > $scope.renderModel.length) {
$scope.contentPickerForm.minCount.$setValidity("minCount", false);
}
else {
$scope.contentPickerForm.minCount.$setValidity("minCount", true);
}
if ($scope.model.config && $scope.model.config.maxNumber && parseInt($scope.model.config.maxNumber) < $scope.renderModel.length) {
$scope.contentPickerForm.maxCount.$setValidity("maxCount", false);
}
else {
$scope.contentPickerForm.maxCount.$setValidity("maxCount", true);
}
});
}
$scope.renderModel = [];
$scope.dialogEditor = editorState && editorState.current && editorState.current.isDialogEditor === true;
//the default pre-values
var defaultConfig = {
multiPicker: false,
showOpenButton: false,
showEditButton: false,
showPathOnHover: false,
startNode: {
query: "",
type: "content",
id: $scope.model.config.startNodeId ? $scope.model.config.startNodeId : -1 // get start node for simple Content Picker
}
};
if ($scope.model.config) {
//merge the server config on top of the default config, then set the server config to use the result
$scope.model.config = angular.extend(defaultConfig, $scope.model.config);
}
//Umbraco persists boolean for prevalues as "0" or "1" so we need to convert that!
$scope.model.config.multiPicker = ($scope.model.config.multiPicker === "1" ? true : false);
$scope.model.config.showOpenButton = ($scope.model.config.showOpenButton === "1" ? true : false);
$scope.model.config.showEditButton = ($scope.model.config.showEditButton === "1" ? true : false);
$scope.model.config.showPathOnHover = ($scope.model.config.showPathOnHover === "1" ? true : false);
var entityType = $scope.model.config.startNode.type === "member"
? "Member"
: $scope.model.config.startNode.type === "media"
? "Media"
: "Document";
$scope.allowOpenButton = entityType === "Document" || entityType === "Media";
$scope.allowEditButton = entityType === "Document";
//the dialog options for the picker
var dialogOptions = {
multiPicker: $scope.model.config.multiPicker,
entityType: entityType,
filterCssClass: "not-allowed not-published",
startNodeId: null,
callback: function (data) {
if (angular.isArray(data)) {
_.each(data, function (item, i) {
$scope.add(item);
});
} else {
$scope.clear();
$scope.add(data);
}
angularHelper.getCurrentForm($scope).$setDirty();
},
treeAlias: $scope.model.config.startNode.type,
section: $scope.model.config.startNode.type
};
//since most of the pre-value config's are used in the dialog options (i.e. maxNumber, minNumber, etc...) we'll merge the
// pre-value config on to the dialog options
angular.extend(dialogOptions, $scope.model.config);
//We need to manually handle the filter for members here since the tree displayed is different and only contains
// searchable list views
if (entityType === "Member") {
//first change the not allowed filter css class
dialogOptions.filterCssClass = "not-allowed";
var currFilter = dialogOptions.filter;
//now change the filter to be a method
dialogOptions.filter = function (i) {
//filter out the list view nodes
if (i.metaData.isContainer) {
return true;
}
if (!currFilter) {
return false;
}
//now we need to filter based on what is stored in the pre-vals, this logic duplicates what is in the treepicker.controller,
// but not much we can do about that since members require special filtering.
var filterItem = currFilter.toLowerCase().split(',');
var found = filterItem.indexOf(i.metaData.contentType.toLowerCase()) >= 0;
if (!currFilter.startsWith("!") && !found || currFilter.startsWith("!") && found) {
return true;
}
return false;
}
}
//if we have a query for the startnode, we will use that.
if ($scope.model.config.startNode.query) {
var rootId = $routeParams.id;
entityResource.getByQuery($scope.model.config.startNode.query, rootId, "Document").then(function (ent) {
dialogOptions.startNodeId = ent.id;
});
} else {
dialogOptions.startNodeId = $scope.model.config.startNode.id;
}
//dialog
$scope.openContentPicker = function () {
$scope.contentPickerOverlay = dialogOptions;
$scope.contentPickerOverlay.view = "treepicker";
$scope.contentPickerOverlay.show = true;
$scope.contentPickerOverlay.submit = function (model) {
if (angular.isArray(model.selection)) {
_.each(model.selection, function (item, i) {
$scope.add(item);
});
}
$scope.contentPickerOverlay.show = false;
$scope.contentPickerOverlay = null;
}
$scope.contentPickerOverlay.close = function (oldModel) {
$scope.contentPickerOverlay.show = false;
$scope.contentPickerOverlay = null;
}
};
$scope.remove = function (index) {
$scope.renderModel.splice(index, 1);
angularHelper.getCurrentForm($scope).$setDirty();
};
$scope.showNode = function (index) {
var item = $scope.renderModel[index];
var id = item.id;
var section = $scope.model.config.startNode.type.toLowerCase();
entityResource.getPath(id, entityType).then(function (path) {
navigationService.changeSection(section);
navigationService.showTree(section, {
tree: section, path: path, forceReload: false, activate: true
});
var routePath = section + "/" + section + "/edit/" + id.toString();
$location.path(routePath).search("");
});
}
$scope.add = function (item) {
var currIds = _.map($scope.renderModel, function (i) {
return i.id;
});
if (currIds.indexOf(item.id) < 0) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon, path: item.path, contentTypeAlias: item.metaData.ContentTypeAlias });
}
};
$scope.clear = function () {
$scope.renderModel = [];
};
var unsubscribe = $scope.$on("formSubmitting", function (ev, args) {
var currIds = _.map($scope.renderModel, function (i) {
return i.id;
});
$scope.model.value = trim(currIds.join(), ",");
});
//when the scope is destroyed we need to unsubscribe
$scope.$on('$destroy', function () {
unsubscribe();
});
//load current data
var modelIds = $scope.model.value ? $scope.model.value.split(',') : [];
entityResource.getByIds(modelIds, entityType).then(function (data) {
//Ensure we populate the render model in the same order that the ids were stored!
_.each(modelIds, function (id, i) {
var entity = _.find(data, function (d) {
return d.id == id;
});
if (entity) {
entity.icon = iconHelper.convertFromLegacyIcon(entity.icon);
$scope.renderModel.push({ name: entity.name, id: entity.id, icon: entity.icon, path: entity.path, contentTypeAlias: entity.metaData.ContentTypeAlias });
}
});
//everything is loaded, start the watch on the model
startWatch();
});
}
angular.module('umbraco').controller("Umbraco.PropertyEditors.CustomContentPickerController", customContentPickerController);

Resources