TinyMCE and AngularJS - not loading after NgSwitch - html

I hope I am clear enough with this request for assistance, as it is hard to explain and I can't post all the code here. I have downloaded code to enable TinyMCE to be used in a NgRepeat with AngularJS:
angular.module('ui.tinymce', [])
.value('uiTinymceConfig', {})
.directive('uiTinymce', ['uiTinymceConfig', function (uiTinymceConfig) {
uiTinymceConfig = uiTinymceConfig || {};
var generatedIds = 0;
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModel) {
var expression, options, tinyInstance;
// generate an ID if not present
if (!attrs.id) {
attrs.$set('id', 'uiTinymce' + generatedIds++);
}
options = {
// Update model when calling setContent (such as from the source editor popup)
setup: function (ed) {
ed.on('init', function (args) {
ngModel.$render();
});
// Update model on button click
ed.on('ExecCommand', function (e) {
ed.save();
ngModel.$setViewValue(elm.val());
if (!scope.$$phase) {
scope.$apply();
}
});
// Update model on keypress
ed.on('KeyUp', function (e) {
ed.save();
ngModel.$setViewValue(elm.val());
if (!scope.$$phase) {
scope.$apply();
}
});
},
mode: 'exact',
elements: attrs.id
};
if (attrs.uiTinymce) {
expression = scope.$eval(attrs.uiTinymce);
} else {
expression = {};
}
angular.extend(options, uiTinymceConfig, expression);
setTimeout(function () {
tinymce.init(options);
});
ngModel.$render = function () {
if (!tinyInstance) {
tinyInstance = tinymce.get(attrs.id);
}
if (tinyInstance) {
tinyInstance.setContent(ngModel.$viewValue || '');
}
};
}
};
}]);
var gwApp = angular.module('gwApp', ['ui.tinymce']);
I don't really understand this code, but it works fine initially. My page starts with a list of Posts. I click on 'Show Reply' for the first post, and using NgSwitch the multiple replies become visible (nested NgRepeat). I submit a new reply message (the reply text is entered using tinymce) using a RESTful API service and a http call (too much code to post here). Then after clicking the submit button for the new reply message, the NgSwitch kicks in again unexpectedly to make the replies no longer visible. When I expand the replies again, the tinymce is just a regular textarea again, and the proper editor is gone.
I know this is not very clear, but I'm hoping someone can make sense of what I've written and can help me solve this problem..

I was having the same problem using ng-switch and ng-show so i added:
scope.$watch('onHidden()',function(){ tinymce.editors = [] });
after the setTimeout function.
Also replace the
ed.on('init',function(args){ ngModel.$render(); });
with
ed.on('init',function(args){ ed.setContent(ngModel.$viewValue); });
and remove the $render function.
This is the link to the working code in JsFiddle

Related

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.

Google Maps not working on tab Ionic

I create tab on Ionic project. When i would access to Google map from another url Tab, it's not working but when i access it directly it works.
First the Ionic part:
The tab showing the map is:
Ionic calls refreshMap() when the user selects the tab.
refreshMap() is:
.controller('MainCtrl', function($scope) {
$scope.refreshMap = function() {
setTimeout(function () {
$scope.refreshMap_();
}, 1); //Need to execute it this way because the DOM may not be ready yet
};
$scope.refreshMap_ = function() {
var div = document.getElementById("map_canvas");
reattachMap(map,div);
};
})
I've implemented reattachMap() looking at the Map.init() method:
function reattachMap(map,div) {
if (!isDom(div)) {
console.log("div is not dom");
return map;
} else {
map.set("div", div);
while(div.parentNode) {
div.style.backgroundColor = 'rgba(0,0,0,0)';
div = div.parentNode;
}
return map;
}
}
function isDom(element) {
return !!element &&
typeof element === "object" &&
"getBoundingClientRect" in element;
}
And that's about it, now when the user switches back to the map tab, it will be there.
Please refer this.
(https://github.com/mapsplugin/cordova-plugin-googlemaps/issues/256/#issuecomment-59784091)

HTML5 File upload with AngularJS

I'm trying to get angular to read the contents of a file that the user selects through an <input type="file" control. Even though angular does not have directives for file upload controls, it should be easy to fix that with a call to $apply:
function MyController($scope) {
$('#myFile').on('change', function() {
var that = this;
$scope.$apply(function() { $scope.files = that.files });
});
}
Unfortunately, the event is never fired. It's like the selector is unable to refer to the correct DOM element: even though the selector finds the element, the list of files is always empty. This also happens if i poke around with the js console. The DOM inspector instead has the file list among its properties.
It's driving me crazy, but the only way I've got it to work so far is to use an inline event handler that assigns to a global variable. Why is the jquery selector returning another item? Is there some template compilation mumbo-jumbo that angular does which confuses selectors?
Here is what I do:
http://plnkr.co/edit/JPxSCyrxosVXfZnzEIuS?p=preview
app.directive('filelistBind', function() {
return function( scope, elm, attrs ) {
elm.bind('change', function( evt ) {
scope.$apply(function() {
scope[ attrs.name ] = evt.target.files;
console.log( scope[ attrs.name ] );
});
});
};
});
template:
<input type="file" filelist-bind name="files"/>
<p>selected files : <pre>{{ files | json }}</pre></p>
This kind of task, you definitely want to make use of directive.
But I think that your main concern is how to access the selected file
objects and my example should clarify that.
If you are looking for file upload with angular you can use this plugin
https://github.com/danialfarid/angular-file-upload
It is basically a directive like tosh's answer that takes care of non-HTML5 browsers with FileAPI flash polyfill and has $http.uploadFile function to upload the actual file via AJAX.
This site uses Angular service for HTML5 File Upload. A simple way is to setup a controller which calls the service and updates the UI when the asynchronous call is completed.
controller:
myapp.controller('fileUploadCtrl', ['$scope', '$q', 'FileInputService', function ($scope, $q, FileInputService) {
$scope.fileInputContent = "";
$scope.onFileUpload = function (element) {
$scope.$apply(function (scope) {
var file = element.files[0];
FileInputService.readFileAsync(file).then(function (fileInputContent) {
$scope.fileInputContent = fileInputContent;
});
});
};
}]);
service:
myapp.service('FileInputService', function ($q) {
this.readFileAsync = function (file) {
var deferred = $q.defer(),
fileReader = new FileReader(),
fileReader.readAsText(file);
fileReader.onload = function (e) {
deferred.resolve(e.target.result);
};
return deferred.promise;
};
});
template:
Choose File <input type="file" onchange="angular.element(this).scope().onFileUpload(this)">
<br />
{{fileInputContent}}
Reference: You can find the full source code and reference on this site.

JavaScript can not call content script JS function

I am developing chrome extension. I loaded JavaScript file successfully but the problem is external JavaScript (which I have loaded) can not call the function of content script files my code is as follows.
$(document).ready(function() {
$('.main_list').click(function()
{
$('.sub_list') .hide();
$(this) .parent() .children('.sub_list') .slideToggle("normal");
});
$('#click') .click(function()
{
$('.sub_list') .hide();
$(this) .parent() .parent() .children('.sub_list').slideToggle("normal");
});
$('#btnnewtask').click(function()
{
showdialog('http://localhost:51967/task.aspx');
});
$('#linknewtask').click(function()
{
showdialog('http://localhost:51967/task.aspx');
});
$('#btnnewcall').click(function()
{
showdialog('http://localhost:51967/call.aspx');
});
$('#linknewcall').click(function()
{
showdialog("http://localhost:51967/call.aspx");
});
$('#btnnewmeeting').click(function()
{
showdialog("http://localhost:51967/meeting.aspx");
});
$('#linknewmeeting').click(function()
{
showdialog("http://localhost:51967/meeting.aspx");
});
});
Showdialog() is function in content script. It is as follow
function showdialog(url)
{
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
xmldoc=xhr.responseXML;
var js=getfile(getjavascript(xmldoc));
for(i=0;i<js.length;i++)
{
loadjscssfile(js[i],"js");
}
var css=getfile(getstylesheet(xmldoc))
for(i=0;i<css.length;i++)
{
loadjscssfile(css[i],"css");
}
document.file.push(
{"url":url,"css":css,"js":js});
document.getElementById("dialogcontainer3").
innerHTML=gethtmldocument(xmldoc);
document.getElementById("blacklayer").style.display="block";
document.getElementById("dialogcontainer3").style.display=
"inline-block";
document.getElementById("dialogcontainer2").style.display="block";
document.getElementById("dialogcontainer1").style.display="block";
}
}
xhr.open("GET",url,true);
xhr.send();
}
But it gives error
Uncaught ReferenceError: showdialog is not defined (program):1
(anonymous function) (program):1
b.event.dispatch (program):3
v.handle (program):3
Content scripts execute in a special environment called an isolated
world. They have access to the DOM of the page they are injected into,
but not to any JavaScript variables or functions created by the page.
It looks to each content script as if there is no other JavaScript
executing on the page it is running on. The same is true in reverse:
JavaScript running on the page cannot call any functions or access any
variables defined by content scripts.
See http://developer.chrome.com/extensions/content_scripts.html#execution-environment
I would suggest trying shared DOM to communicate between the content script and the page or Message Passing.
An example of code on the page would be:
function showDialog(url) {
window.postMessage({
type: "FROM_PAGE",
text: url
}, "*");
}
And in the contentscript:
// This function will NOT collide with showDialog of the page:
function showDialog(url) {
/* ... */
}
window.addEventListener("message", function (event) {
// We only accept messages from ourselves
if (event.source != window) { return; }
// Make sure we're looking at the correct event:
if (event.data.type && (event.data.type == "FROM_PAGE")) {
showDialog(event.data.text);
}
}, false);
I haven't tested the above, so please consider it to be pseudocode. A similar example is available here: http://developer.chrome.com/extensions/content_scripts.html#host-page-communication

malsup jquery form submit on select change

I'm using Malsup's excellent Form plugin to dynamically load search results onto the same page.
It works great with a standard form submit, however I have 2 select elements in my form and would love for the results to update as the select is changed.
My code at the moment is thus:
$(document).ready(function() {
var options = {
target: '#bands-results',
beforeSubmit: showRequest
};
$('#bandsearch').ajaxForm(options);
});
// Show loading message and submit form
function showRequest(formData, jqForm, options) {
$('#bands-results').prepend('<span>Searching</span>');
return true;
}
I haven't seen other examples that do the same.
Help appreciated.
Got it licked with this
$(document).ready(function() {
$("#genre-filter").change(function() {
$("#band_search").submit();
});
// bind to the form's submit event
$('#band_search').ajaxForm({
beforeSubmit: showRequest,
target: '#band_list',
success: function() {
$('#premlim').hide();
}
});
})
function showRequest(formData, jqForm, options) {
return true;
}