ACE static highlight without using PHP tags - static

This is an example of using ext-static-highlight.js of ACE Editor. How would I set the inline option to true, so I can avoid using PHP tags when highlighting the code?
<script>
var highlight = ace.require("ace/ext/static_highlight")
var dom = ace.require("ace/lib/dom")
function qsa(sel) {
return Array.apply(null, document.querySelectorAll(sel));
}
qsa(".code").forEach(function (codeEl) {
highlight(codeEl, {
mode: codeEl.getAttribute("ace-mode"),
theme: codeEl.getAttribute("ace-theme"),
startLineNumber: 1,
showGutter: codeEl.getAttribute("ace-gutter"),
trim: true
}, function (highlighted) {
});
});
</script>

You need to pass an object to the highlight function as a mode {path: "ace/mode/php", inline: true}.
so use something like this:
<script>
var highlight = ace.require("ace/ext/static_highlight")
var dom = ace.require("ace/lib/dom")
function qsa(sel) {
return Array.apply(null, document.querySelectorAll(sel));
}
qsa(".code").forEach(function (codeEl) {
var mode = codeEl.getAttribute("ace-mode");
if (mode == "php-inline")
mode = {path: "ace/mode/php", inline: true}
highlight(codeEl, {
mode: mode,
theme: codeEl.getAttribute("ace-theme"),
startLineNumber: 1,
showGutter: codeEl.getAttribute("ace-gutter"),
trim: true
}, function (highlighted) {
});
});
</script>

Related

Role Based Access Control in AngularJS Blur-Admin template

How to implement Role Based Access Control in Blur-Admin template for angularJS? Where to define roles? Which files are concerned?
Perfect and Working Solution! This solution basically provides restricted access to the roles allowed for that component.
define params in all of your main modules in this way - (for example) -
(function() {
'use strict';
angular.module('BlurAdmin.pages.components', [
'BlurAdmin.pages.components.mail',
// 'BlurAdmin.pages.components.timeline',
// 'BlurAdmin.pages.components.tree',
// 'BlurAdmin.pages.components.fileUpload',
])
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('main.components', {
url: '/components',
template: '<ui-view autoscroll="true" autoscroll-body-top></ui-view>',
abstract: true,
title: 'Components',
sidebarMeta: {
icon: 'ion-gear-a',
order: 100,
},
authenticate: true,
params: { // <-- focusing this one
authRoles: ['admin'] // <-- roles allowed for this module
}
});
}
})();
Modify baSidebar.service.js, add a new function getAuthorizedMenuItems just below getMenuItems (for easy understanding). And then just add a single parameter authRoles in defineMenuItemStates().
So, getAuthorizedMenuItems() will contain following code -
this.getAuthorizedMenuItems = function(user) {
var states = defineMenuItemStates();
var menuItems = states.filter(function(item) {
return item.level == 0 && _.includes(item.authRoles, user.role);
});
menuItems.forEach(function(item) {
var children = states.filter(function(child) {
return child.level == 1 && child.name.indexOf(item.name) === 0;
});
item.subMenu = children.length ? children : null;
});
return menuItems.concat(staticMenuItems);
};
And updated defineMenuItemStates() will be -
function defineMenuItemStates() {
return $state.get()
.filter(function(s) {
return s.sidebarMeta;
})
.map(function(s) {
var meta = s.sidebarMeta;
return {
name: s.name,
title: s.title,
level: ((s.name.match(/\./g) || []).length - 1),
order: meta.order,
icon: meta.icon,
stateRef: s.name,
authRoles: s.params ? s.params.authRoles : undefined // <-- added this
};
})
.sort(function(a, b) {
return (a.level - b.level) * 100 + a.order - b.order;
});
}
Now, it's time to use the newly added method getAuthorizedMenuItems in BaSidebarCtrl.js. Use it this way -
// FYI, I got userCreds in BaSidebarCtrl as following -
var userCreds = localStorage.getObject('dataUser');
// note that getMenuItems is just replaced with getAuthorizedMenuItems(userCreds)
// $scope.menuItems = baSidebarService.getMenuItems();
$scope.menuItems = baSidebarService.getAuthorizedMenuItems(userCreds);
So, your user object will look something like this -
var userCreds = {
userName: 'test#mail.com',
passWord: 'testpwd',
role: 'admin'
};
That's it!

Kendo-ui angular directive on editor

I'm trying to attach an angular directive to `
{
field:"stateID",
hidden: true,
title: "State",
editor: function (container, options) {
var _statesDirective = $('<div><my-states></my-states></div>');
_statesDirective.appendTo(container);
}`
My diretive looks like this:
appRoot.directive('myStates', function () {
return {
restrict: 'EA',
templateUrl: 'directivesHTML/ddStates.html',
scope:false,
controller: function ($scope)
{
var dsStates = new kendo.data.DataSource({
autoBind: false,
page: 1,
transport: {
read: {
url: "api/util/getStates",
dataType: "json"
}
},
schema: {
model: {
id: "stateID",
fields: {
stateID: { type: 'string' },
name: { type: "string" }
}
}
}
});
dsStates.read().then(function () {
$('#ddStates')
.kendoDropDownList({
dataTextField: "name",
dataValueField: "stateID",
dataSource: dsStates,
optionLabel: '--',
change: function (e) {
}
});
});
}
};
});
For some weird reason, it wont work, if I put the directive someplace else, any outside html page, it works just fine, but not from here. I thought it could be the version, upgraded it to the latest one for this month to no avail.
Any clues ?
-thanks,
You need to compile your html before appending it (using $compile service).
So in your editor: function,
// Specify what it is we'll be compiling.
var to_compile = '<div><my-states></my-states></div>';
// Compile the tag, retrieving the compiled output.
var _statesDirective = $compile(to_compile)($scope);
// Ensure the scope and been signalled to digest our data.
$scope.$digest();
// Append the compiled output to the page.
$compiled.appendTo(_statesDirective);
For more reference, Angular Docs for $compile
Also, how can we use $compile outside a directive in Angularjs

Running reveal.js in mdDialog or ngDialog

Been trying to figure out a way to do this, and THINK I have figured out the issue, but have no clue what can be done.
Basically, I want a popup window to appear ala mdDialog or ngDialog, basically a nice window with loads of bits. But the issue is that if I do that, whatever is loaded in mdDialog or ngDialog as a template can only be HTML. It will not allow me to start reveal.js internally.
I have tried with both angular material and angular dialog. And both have the same issue.
Firstly, our very simple self contained reveal html.
<md-dialog aria-label="How to consume" ng-cloak>
<link rel="stylesheet" href="/bower_components/reveal.js/css/reveal.css">
<div>
<div style="background-color: #00B700; height: 400px; width: 600px" class="reveal" >
<div class="slides">
<section><H1>This is one</H1></section>
<section><H1>This is two</H1></section>
<section><H1>This is three</H1></section>
<section><H1>This is four</H1></section>
</div>
</div>
</div>
<script src="/bower_components/reveal.js/lib/js/head.min.js"></script>
<script src="/bower_components/reveal.js/js/reveal.js"></script>
<script>
console.log("Trying to load now")
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{
src: '/bower_components/reveal.js/lib/js/classList.js', condition: function () {
return !document.body.classList;
}
},
{
src: '/bower_components/reveal.js/plugin/markdown/marked.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: '/bower_components/reveal.js/plugin/markdown/markdown.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: '/bower_components/reveal.js/plugin/highlight/highlight.js',
async: true,
condition: function () {
return !!document.querySelector('pre code');
},
callback: function () {
hljs.initHighlightingOnLoad();
}
},
{src: '/bower_components/reveal.js/plugin/zoom-js/zoom.js', async: true},
{src: '/bower_components/reveal.js/plugin/notes/notes.js', async: true}
]
});
Reveal.addEventListener('ready', function (event) {
console.log("I have now entered " + event.currentSlide)
// event.currentSlide, event.indexh, event.indexv
});
</script>
</md-dialog>
If you open that in a browser (and have reveal installed under bower_component) it works nicely.
If you open it in mdDialog or ndDialog nothing happens (it never fires the
} else if ( type === 'ngDialog') {
console.log("Attempting to open ngDialog")
ngDialog.open({ template: '/modals/consumer', controller: 'revealController'});
} else if ( type === 'mdDialog') {
$mdDialog.show({
controller: 'revealController',
templateUrl: '/modals/consumer',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: useFullScreen
})
.then(function (answer) {
console.log('You said the information was "' + answer + '".');
if(answer === 'login'){
$scope.external = false
$location.url('/int/index');
}
}
I also tried doing it via a controller, so same html using a controller as follows:
ngDialog.open({ template: '/modals/consumer', controller: 'displayRevealController'});
And trying to make a nice controller to call reveal:
Controller:
app.controller('displayRevealController', function($scope, $http, $mdDialog){
console.log("I am so initialising")
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{
src: '/bower_components/reveal.js/lib/js/classList.js', condition: function () {
return !document.body.classList;
}
},
{
src: '/bower_components/reveal.js/plugin/markdown/marked.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: '/bower_components/reveal.js/plugin/markdown/markdown.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: '/bower_components/reveal.js/plugin/highlight/highlight.js',
async: true,
condition: function () {
return !!document.querySelector('pre code');
},
callback: function () {
hljs.initHighlightingOnLoad();
}
},
{src: '/bower_components/reveal.js/plugin/zoom-js/zoom.js', async: true},
{src: '/bower_components/reveal.js/plugin/notes/notes.js', async: true}
]
});
Reveal.addEventListener('ready', function (event) {
console.log("I have now entered " + event.currentSlide)
// event.currentSlide, event.indexh, event.indexv
});
});
But then I get an error message indicating that it cant find the DOM
TypeError: Cannot read property 'classList' of null

How to use $compile in angularjs with new element

I am trying to develop a friendly dialog plugin with angularjs & bootstrap.
I found dialog based in directive was not that easy to use, add a html tag first and define controller and variable, that is too complicated.
So I intend to add a method to angular, create new element dynamic and set variable to root scope, but there seems to be some problems about compile.
Here is mainly code:
var defaultOption = {
title: 'Title',
content: 'Content',
backdrop: false,
buttons: [],
$dom: null
};
var prefix = '__dialog',
index = 0;
var newId = function (scope) {
var id = prefix + index;
if (!scope[id]) return id;
index++;
return arguments.callee(scope);
};
var app = angular.module("app", []);
app.directive('bootstrapModal', ['$compile', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: {
bootstrapModal: '='
},
link: function (scope, $ele) {
var $dom = $(defaultTemplate),
body = $ele.children();
if (body.length) $dom.find('.modal-body').html(body);
$ele.replaceWith($dom);
$compile($dom)(scope);
scope.bootstrapModal.$dom = $dom;
}
};
}]);
angular.ui = {};
angular.ui.dialog = function (args) {
var $body = angular.element(document.body),
$rootScope = $body.scope().$root,
option = $.extend({}, defaultOption, args);
option.id = option.id || newId($rootScope);
option.show = function () {
this.$dom.modal('show');
};
option.hide = function () {
this.$dom.modal('hide');
};
$body.injector().invoke(function ($compile) {
$rootScope[option.id] = option;
var dialog = '<div bootstrap-modal="{0}"></<div>'.format(option.id);
var html = $compile(dialog)($rootScope);
$('body').append(html);
});
return option;
};
$(function () {
angular.ui.dialog({ //test
title: 'Alert',
content: 'test content for alert',
buttons: [{
name: 'Close',
focus: true
}]
}).show();
});
The entire code is too long, so I put it in JSFIDDLE
Thanks!
Put a $rootScope.$apply(function() { ... }) around your code where you compile your dialog in injector().invoke(...).
Updated fiddle

Plupload + AngularJS UI modal doesn't work in IE

I've already seen a lot of articles about plupload and modal dialogs in old versions of IE, but any of them had a solution for my problem. I'm using AngularJS UI to open modals which contain the container div of plupload, and I need to do this work in this way.
I've tried all the solutions: uploader.refresh(), I've used require.js to load the plupload script when the dialog was already opened, but I still haven't found one that works.
Here's the function of the controller that calls the modal dialog:
$scope.EnviarNovoAnexoClick = function () {
var modalInstance = $modal.open({
templateUrl: '/Dialog/EnviarAnexo',
controller: 'EnviarAnexoDialogController',
resolve: {
documentoId: function () {
return $scope.documentoId;
}
}
});
modalInstance.result.then(function (anexo) {
$scope.documento.anexos.push(anexo);
}, function () {//dismiss callback
});
}
Here's the function that calls the uploader:
require(["/Scripts/plupload.full.js"], function (util) {
$scope.anexoUploader = new plupload.Uploader({
runtimes: 'gears,html5,flash,silverlight,browserplus,html4',
browse_button: 'anexoBtUpload',
container: 'anexoUploadDiv',
unique_names: true,
multi_selection: false,
max_file_size: '150mb',
chunk_size: '64kb',
url: '/Documento/Upload',
flash_swf_url: '/Scripts/plupload.flash.swf',
silverlight_xap_url: '/Scripts/plupload.silverlight.xap',
resize: { width: 320, height: 240, quality: 90 },
filters: [
{ title: "PDFs ", extensions: "pdf" },
{ title: "Imagens", extensions: "jpg,gif,png" },
{ title: "Zips", extensions: "zip" },
{ title: "Todos", extensions: "*" }
],
init: {
FilesAdded: function (up, files) {
if ($scope.uploadDocumento == null) {
$scope.showOrigemAnexo = false;
$scope.novoAnexo.upload = {};
$scope.InicializaUpload($scope.novoAnexo.upload);
$scope.uploadDocumento = $scope.novoAnexo.upload;
}
var fileName = $scope.anexoUploader.files[$scope.anexoUploader.files.length - 1].name;
$scope.uploadDocumento.nome = fileName;
$scope.novoAnexo.descricao = dotlessName(fileName);
$scope.$apply();
up.refresh(); // Reposition Flash/Silverlight
up.start();
},
UploadProgress: function (up, file) {
$scope.uploadDocumento.size = file.size;
$scope.uploadDocumento.percentage = file.percent;
$scope.$apply();
},
FileUploaded: function (up, file, response) {
$scope.uploadDocumento.id = file.id;
$scope.uploadDocumento.size = file.size;
$scope.$apply();
}
}
});
$scope.anexoUploader.init();
});
The file dialog is opening in Chrome, IE10 and Firefox, but I need that it works on IE9 and 8.
Thanks (:
This has something to do with caching and dynamically loaded script tag.
Solution that worked for me:
Add this directive:
.directive('cachedTemplate', ['$templateCache', function ($templateCache) {
"use strict";
return {
restrict: 'A',
terminal: true,
compile: function (element, attr) {
if (attr.type === 'text/ng-template') {
var templateUrl = attr.cachedTemplate,
text = element.html();
$templateCache.put(templateUrl, text);
}
}
};
}])
Declare your modal content in
<div data-cached-template="myInnerModalContent.html" type="text/ng-template">
<!-- content -->
</div>
You may need this style as well:
*[type="text/ng-template"]{
display: none;
}
In controller:
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'ModalContent.html',
controller: modalInstanceCtrl
});
};
Reference: http://blog.tomaszbialecki.info/ie8-angularjs-script-cache-problem/

Resources