AngularJS: window service and directive - angularjs

I'm learning AngularJS and I want to create a custom service and directive to show window view which I can close, minimize, maximize, drag and resize. I wrote something but I am not sure if this is correct, especially, when I use ng-view while changing route I had to add
scope.$on('$routeChangeStart', function (next, current) {
});
to my code and ngRoute to the dependecies list to see the view, but I didn't add anything to respond to it and I am not sure how this works.
I wanted also add possibility to close window on esc but when I added this functionality closing window with animation stop working.
Could someone take a look at the code and tell me what is wrong or missed or explain something?
(function (window, angular) {
'use strict';
var module = angular.module('bbWindow', []);
module.provider('bbWindow', function () {
var defaults = this.defaults = {
id: null,
controller: null,
scope: null,
windowTitle: null,
windowContent: null,
className: 'bbwindow-theme-default',
position: 'top', // position of the window: 'top', 'center', 'bottom'
size: 'medium', // size of the window: 'small', 'medium', 'large'
showButtons: true,
showCloseButton: true,
showMinimizeButton: true,
showMaximizeButton: true,
showBackdrop: false,
closeByBackdropClick: false,
closeByEscape: true,
onClose: null,
praventClosing: false,
animation: 'am-fade-and-scale', // use animations from angular-motion, eg. am-slide-top, am-fade-and-scale, am-flip-x
backdropAnimation: 'am-fade',
template: 'common/bbwindow/bbwindow.tpl.html',
plainTemplate: false,
contentTemplate: null,
plainContentTemplate: false,
draggable: true,
dragOpacity: 0.35,
resizable: true,
resizeMinHeight: 150,
resizeMinWidth: 330
};
var openedWindows = [],
globalId = 0,
zIndex = 1000,
minimizedWindowPositions = [],
topId = 0,
defers = []; // used to resolve when window is closed
this.$get = ['$rootScope',
'$document',
'$compile',
'$q',
'$templateCache',
'$http',
'$timeout',
'$sce',
'$animate',
'$route',
'$log',
function ($rootScope, $document, $compile, $q, $templateCache, $http, $timeout, $sce, $animate, $route, $log) {
var body = $document.find('body');
// private methods
function onKeyUp(event) {
event.stopPropagation();
if (event.keyCode === 27) {
if (topId) {
bbwindow.close(topId);
}
}
}
function fetchTemplate(template, plain) {
if (plain) {
return $q.when(template);
}
return $q.when($templateCache.get(template) || $http.get(template))
.then(function (res) {
if (angular.isObject(res)) {
$templateCache.put(template, res.data);
return res.data;
}
return res;
});
}
// find elements in element or document for specified selectors
function findElement(selectors, element) {
return angular.element((element || document).querySelectorAll(selectors));
}
// get height of the screen
function getDocHeight() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
function getElementPositionObject(element) {
return {
width: element.css('width'),
height: element.css('height'),
top: element.css('top'),
left: element.css('left'),
margin: element.css('margin')
};
}
// find the minimized window position in the array and remove it
function removeMinimizedWindowPosition(windowElement) {
var left = parseInt(windowElement.css('left')),
top = parseInt(windowElement.css('top')),
i,
position = -1;
for (i = 0; i < minimizedWindowPositions.length; i++) {
if (minimizedWindowPositions[i][0] == left && minimizedWindowPositions[i][1] == top) {
position = i;
break;
}
}
if (position > -1) {
minimizedWindowPositions.splice(position, 1);
}
}
// public object returned from service
var bbwindow = {
open: function (config) {
var self = this,
options = angular.copy(defaults);
config = config || {};
angular.extend(options, config);
globalId += 1;
var id = options.id || 'bbwindow' + globalId;
topId = id;
var defer = $q.defer();
defers[id] = defer;
var scope = options.scope && angular.isObject(options.scope) ? options.scope.$new() : $rootScope.$new();
// Support scope as string options
angular.forEach(['windowTitle', 'windowContent'], function (key) {
if (options[key]) {
scope[key] = $sce.trustAsHtml(options[key]);
}
});
scope.showButtons = options.showButtons;
scope.showCloseButton = options.showCloseButton;
scope.showMinimizeButton = options.showMinimizeButton;
scope.showMaximizeButton = options.showMaximizeButton;
scope.close = function () {
scope.$$postDigest(function () {
if (!options.preventClosing) {
bbwindow.close(id);
}
if (options.onClose && $.isFunction(options.onClose)) {
options.onClose();
}
});
};
scope.maximize = function () {
scope.$$postDigest(function () {
bbwindow.maximize(id);
});
};
scope.minimize = function () {
scope.$$postDigest(function () {
bbwindow.minimize(id);
});
};
scope.$on('$routeChangeStart', function (next, current) {
});
// featch main window template
var templatePromise = fetchTemplate(options.template, options.plainTemplate);
// check if the user provided template for content and fetch it
if (options.contentTemplate) {
templatePromise = templatePromise.then(function (template) {
var templateElement = angular.element(template);
if (templateElement) {
// fetch content template
return fetchTemplate(options.contentTemplate, options.plainContentTemplate).then(function (contentTemplate) {
var contentElement = findElement('[data-ng-bind="windowContent"]', templateElement[0]);
if (contentElement) {
contentElement.removeAttr('data-ng-bind').html(contentTemplate);
return templateElement[0].outerHTML;
}
});
}
});
}
templatePromise.then(function (template) {
if (template) {
var windowElement = $compile(template)(scope);
scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest();
windowElement.attr('id', id);
if (options.controller && angular.isString(options.controller)) {
windowElement.attr('data-ng-controller', options.controller);
}
// set default theme class
windowElement.addClass(options.className);
// set initial positioning
windowElement.addClass(options.position);
// set initial size of the window
windowElement.addClass(options.size);
// add drag option if enabled
if (options.draggable) {
$(windowElement).draggable({
addClasses: false,
cancel: "input,textarea,button,select,option,.bbwindow-content,.bbwindow-header-buttons",
opacity: options.dragOpacity
});
// jquery draggable plugin sets position to relative and then there is
// problem while resizing element, so change position to absolute
$(windowElement).css('position', 'absolute');
} else {
// if the window won't be draggable, then find h4 element in the header
// and change cursor from move to normal
$(windowElement).find('.bbwindow-header h4').css('cursor', 'default');
}
// add resize option if enabled
if (options.resizable) {
$(windowElement).resizable({
handles: "all",
minHeight: options.resizeMinHeight,
minWidth: options.resizeMinWidth
});
if (options.position == 'center') {
$(windowElement).css('transform', 'inherit');
}
}
if (options.closeByEscape) {
//body.off('keyup');
//windowElement.on('keyup', onKeyUp);
}
if (options.animation) {
windowElement.addClass(options.animation);
}
windowElement.on('mousedown', function () {
topId = id;
windowElement.css('z-index', zIndex++);
});
$animate.enter(windowElement, body, null, function () {
});
}
});
return {
id: id,
closePromise: defer.promise,
close: function() {
bbwindow.close(id);
}
};
},
confirm: function(config) {
var defer = $q.defer();
var options = {
closeByBackdropClick: false,
closeByEscape: false
};
angular.extend(options, config);
options.scope = angular.isObject(options.scope) ? options.scope.$new() : $rootScope.$new();
options.scope.confirm = function(value) {
defer.resolve(value);
window.close();
};
var window = bbwindow.open(options);
window.closePromise.then(function () {
defer.reject();
});
return defer.promise;
},
close: function (id) {
var windowElement = angular.element(document.getElementById(id));
if (windowElement) {
var isMinimized = windowElement.scope().isMinimized || false;
if (isMinimized) {
removeMinimizedWindowPosition(windowElement);
}
if (defers[id]) {
defers[id].resolve({
id: id,
window: windowElement
});
delete defers[id];
}
windowElement.scope().$destroy();
$animate.leave(windowElement, function () {
});
}
},
maximize: function (id) {
var windowElement = angular.element(document.getElementById(id));
if (windowElement) {
var isMinimized = windowElement.scope().isMinimized || false;
if (isMinimized) {
return;
}
var bodyWidth = $('body').width(),
bodyHeight = getDocHeight(),
elementWidth = parseInt(windowElement.css('width')),
elementHeight = parseInt(windowElement.css('height'));
if (windowElement.scope().lastPosition && elementWidth == bodyWidth && elementHeight == bodyHeight) {
var lastPosition = windowElement.scope().lastPosition;
$(windowElement).animate({
position: 'absolute',
width: lastPosition.width,
height: lastPosition.height,
top: lastPosition.top,
left: lastPosition.left,
margin: lastPosition.margin
}, 200);
windowElement.scope().lastPosition = null;
} else {
windowElement.scope().lastPosition = getElementPositionObject(windowElement);
$(windowElement).animate({
position: 'fixed',
width: '100%',
height: '100%',
top: '0',
left: '0',
margin: '0'
}, 200);
}
}
},
minimize: function (id) {
var windowElement = angular.element(document.getElementById(id));
if (windowElement) {
var bodyWidth = $('body').width(),
bodyHeight = getDocHeight(),
isMinimized = windowElement.scope().isMinimized || false;
if (isMinimized) {
var lastPosition = windowElement.scope().lastPositionForMinimizedElement;
removeMinimizedWindowPosition(windowElement);
$(windowElement).animate({
width: lastPosition.width,
height: lastPosition.height,
top: lastPosition.top,
left: lastPosition.left,
margin: lastPosition.margin
}, 200);
windowElement.scope().isMinimized = false;
windowElement.scope().lastPositionForMinimizedElement = null;
$(windowElement).draggable('enable');
$(windowElement).resizable('enable');
} else {
windowElement.scope().lastPositionForMinimizedElement = getElementPositionObject(windowElement);
var headerHeight = $(windowElement).find('.bbwindow-header').css('height');
var top = bodyHeight - parseInt(headerHeight);
var width = 200;
var left = 0;
var i = 0;
var found = false;
// find position for minimized window
do {
i++;
if (minimizedWindowPositions.length == 0) {
found = true;
break;
}
var positions = minimizedWindowPositions.filter(function (pos) {
return pos[0] == left && pos[1] == top;
});
if (positions.length > 0) {
left = i * width;
if (left + width >= bodyWidth) {
i = 0;
left = 0;
top -= parseInt(headerHeight);
}
} else {
found = true;
}
} while (!found);
minimizedWindowPositions.push([left, top]);
$(windowElement).animate({
height: headerHeight,
left: left + 'px',
top: top + 'px',
margin: '0',
width: width + 'px'
}, 200);
windowElement.scope().isMinimized = true;
$(windowElement).draggable('disable');
$(windowElement).resizable('disable');
}
}
}
};
return bbwindow;
}];
});
module.directive('bbWindowMain', ['$sce', 'bbWindow', function ($sce, bbWindow) {
return {
restrict: 'E',
scope: true,
link: function (scope, element, attr, transclusion) {
var options = {scope: scope};
angular.forEach(['id', 'className', 'position', 'size', 'animation', 'template', 'contentTemplate'], function (key) {
if (angular.isDefined(attr[key])) {
options[key] = attr[key];
}
});
angular.forEach(['windowTitle', 'windowContent'], function (key) {
attr[key] && attr.$observe(key, function (newValue, oldValue) {
scope[key] = $sce.trustAsHtml(newValue);
});
});
bbWindow.open(options);
}
};
}]);
})(window, window.angular);

Related

Add focus/blur event in directive not working with templateUrl

I'm on a mysterious bug since last friday and perhaps you have an explanation.
I have a directive define like that :
//------------------------------------------------------------------------------
// fl-main-menu
// Type: Element
// Description: Creates a...
//------------------------------------------------------------------------------
uiModule.directive('flNavMenu', ['$rootScope', function ($rootScope) {
//-------------------------
// CONTROLLER
//-------------------------
var componentController = function ($scope, $element, $state, localize, $stateParams, StateManager)
{
$scope.isMenuOpened = false;
$scope.buttonsData = [
{
name: "Games",
data: {
type: "navMenuIconButton",
label: "menu_Games",
imgUrl: "./images/ic-controller-w.svg",
imgUrlOver: "./images/ic-controller-w.svg",
cb: function () { StateManager.display("gameCategories"); }
}
},
{
name: "News",
data: {
type: "navMenuIconButton",
label: "News",
imgUrl: "./images/ic-news-w.svg",
imgUrlOver: "./images/ic-news-w.svg",
cb: function () { StateManager.display("newsList", { spaceId: '', newsIndex: 0}); }
}
}
];
var updateNavButtons = function (){
$scope.navButtons = [{
imgUrl: "./images/ic-menu-w.svg",
label: "Menu_Close"
}
];
if(app.fromGame){
$scope.navButtons.push({
imgUrl: "./images/navBar-ico-Y-w.svg",
label: "Btn_BackToGame"
}
);
}
};
updateNavButtons();
$scope.unregisterStageChange = $rootScope.$on('$stateChangeSuccess', function (event) {
var buttons: any = document.getElementsByClassName('fl-component navmenu-item-button');
var element : any;
if ($state.includes("newsList")) {
if (!$stateParams.spaceId)
element = buttons[2];
else
element = buttons[1];
}
else if ($state.includes("main")) {
element = buttons[0];
}
else {
element = buttons[1];
}
if (element) {
$element[0].children[0]._lastFocusElement = element;
$element[0].children[0]._focusables = buttons;
}
});
var fromGame = false;
$scope.app = app;
$scope.unwatchFromGame = $scope.$watch("app.fromGame", function (newValue, oldValue) {
if (newValue === fromGame) {
return;
}
updateNavButtons();
});
function openCloseMenu()
{
if ($element[0].style.display != 'none')
{
if ($rootScope.isVideoPlayerOpen)
{
$rootScope.$emit("closeVideo");
}
if (!$scope.isMenuOpened)
{
$scope.onViewOver();
}
else
{
$scope.onViewOut();
}
}
};
function isMenuButtonPressed(keyPressed)
{
var keyMapping = platform.getKeyMapping();
if ((platform.isPC() && keyPressed == keyMapping.Space)
|| (platform.isMobile()
&& keyPressed == keyMapping.Enter))
{
return true;
}
return false;
};
function onKeyUp(event)
{
if (isMenuButtonPressed(event.keyCode))
{
openCloseMenu();
}
};
EventManager.addEventListener(window.document.body, BaseEventType.KEYUP, BaseEventPhase.CAPTURE_PHASE, onKeyUp, this);
$scope.$on('$destroy', () => {
$scope.unwatchFromGame();
$scope.unregisterStageChange();
$element[0].children[0].onKeyDownEvent = undefined;
EventManager.removeEventListener(window.document.body, BaseEventType.KEYUP, BaseEventPhase.CAPTURE_PHASE, onKeyUp, this);
TweenMax.killTweensOf($element[0].children[0]);
TweenMax.killTweensOf($element[0].children[1]);
})
};
//-------------------------
// LINK
//-------------------------
var componentLink = function (scope, element)
{
var offset = 185;
var menu = element[0].children[0];
var tongue = element[0].children[1];
var wrapper = document.getElementById('wrapper');
/**
* Close the tongue and open the menu
*/
scope.onViewOver = function () {
var width = menu.scrollWidth;
TweenMax.killTweensOf(menu);
TweenMax.killTweensOf(tongue);
//Make the tongue disapear, and the menu appear
TweenMax.to(tongue, 0.2, { alpha: 0, ease: Quad.easeOut });
TweenMax.to(menu, 0.2, { alpha: 1, ease: Quad.easeIn });
//Open menu animation (css transition)
offset = $rootScope.app.isSnapMode ? 250 : 95;
if (wrapper) wrapper.style.left = ((width / 2) + offset) + 'px';
menu.style.left = '0px';
scope.isMenuOpened = true;
};
/**
* Close the menu and open the tongue
*/
scope.onViewOut = function () {
TweenMax.killTweensOf(menu);
TweenMax.killTweensOf(tongue);
//Make the menu disapear, and the tongue appear
TweenMax.to(tongue, 0.2, { alpha: 1.0, ease: Quad.easeIn });
TweenMax.to(menu, 0.1, { alpha: 0, ease: Expo.easeIn, delay:0.2});
//Close menu animation (css transition)
if (wrapper) wrapper.style.left = '0px';
menu.style.left = '-480px';
scope.isMenuOpened = false;
};
element[0].firstChild.onBlurEvent = scope.onViewOut;
element[0].firstChild.onFocusEvent = scope.onViewOver;
};
//-------------------------
// TEMPLATE
//-------------------------
var componentTemplate = '<div class="navmenu-wrapper">' +
'<div id="navmenu" class="fl-container navmenu navmenu-fixed-left fl-fixed-container">'+
'<div>'+
'<ul>' +
'<fl-nav-menu-item ng-repeat="buttonData in buttonsData" nav-item-data="buttonData" class="text - center" id="ID{{$index}}"></fl-nav-menu-item>' +
'</ul>'+
'<ul class="navmenu-nav-icons">' +
'<div ng-repeat="navButton in navButtons" class="navmenu-nav-icon">' +
'<img ng-src="{{navButton.imgUrl}}">' +
'<span>{{navButton.label | i18n }}</span>' +
'</div>' +
'</ul>'+
'</div>'+
'<div>'+
'</div>'+
'</div>'+
'<img src="./images/btn_drawer_menu.png" class="navmenu-tongue" id="navmenu-tongue">' +
'</div>';
//-------------------------
// RETURN
//-------------------------
return {
restrict: "E",
controller: ["$scope", "$element", '$state', 'localize', '$stateParams', 'UplayTracking', 'StateManager', componentController],
link: componentLink,
template: componentTemplate,
replace:true
}
}]);
You can see in the componentLink method that we had manually methods for onFocus/onBlur event:
element[0].firstChild.onBlurEvent = scope.onViewOut;
element[0].firstChild.onFocusEvent = scope.onViewOver;
The problem is : if I change the template of this directive for a templateUrl (so put all html in a separate file), when the onBlur/onFocus event are raised, our methods are not called. Do you have an idea why ? Thanks for your help !
-We use templateCache to loading our html template.
-I already verify if my element[0] is the same with ou without templateUrl and yes it's the same element.

When open a modal on page load but modal open two times

I want to develop a angularjs web application where I need when url has a query string id then open a modal against the id. The modal open successfully but problem is the modal open twitch time. So Please suggest me how to prevent to open modal two times and ensure that the modal open only one time when query string has a id. My code is below:
myApp.controller('othersObjectiveListController', ['$scope', '$uibModal', 'EmployeeObjectiveService', '$routeParams', function ($scope, $uibModal, EmployeeObjectiveService, $routeParams) {
var items = [];
for (i = 0; i < 100; i++) {
items[i] = i;
}
$scope.test = items;
$scope.StatusBy = [{ id: 1, value: true, label: 'Approve' }, { id: 2, value: false, label: 'Pending' }];
//Angular Code for Multiple column show and hide
$scope.dropConfig = {
scrollable: true,
scrollableHeight: '340px',
showCheckAll: false,
showUncheckAll: false
}
EmployeeObjectiveService.getOtherObjectiveColumnList().then(function (response) { $scope.AllColumn = response.data });
EmployeeObjectiveService.getOtherSelectedColumn().then(function (response) { $scope.SelectedColumn = response.data });
EmployeeObjectiveService.getOtherObjectiveSelected().then(function (response) { $scope.SelectCol = response.data });
function changeColumnViewShow(item) {
if (item.id == 1) {
$scope.SelectCol.EmployeeID = !$scope.SelectCol.EmployeeID;
} else if (item.id == 2) {
$scope.SelectCol.EmployeeName = !$scope.SelectCol.EmployeeName;
} else if (item.id == 3) {
$scope.SelectCol.Code = !$scope.SelectCol.Code;
} else if (item.id == 4) {
$scope.SelectCol.Title = !$scope.SelectCol.Title;
} else if (item.id == 5) {
$scope.SelectCol.KPI = !$scope.SelectCol.KPI;
} else if (item.id == 6) {
$scope.SelectCol.Target = !$scope.SelectCol.Target;
} else if (item.id == 7) {
$scope.SelectCol.Weight = !$scope.SelectCol.Weight;
} else if (item.id == 8) {
$scope.SelectCol.Note = !$scope.SelectCol.Note;
} else if (item.id == 9) {
$scope.SelectCol.Status = !$scope.SelectCol.Status;
}
}
$scope.changeEvents = {
onItemSelect: function (item) {
changeColumnViewShow(item);
},
onItemDeselect: function (item) {
changeColumnViewShow(item);
}
};
//End Column hide show function
// This Section for Pagination for Pending List
$scope.ViewItems = [{ value: 10, id: 10 }, { value: 20, id: 20 }, { value: 50, id: 50 }, { value: 100, id: 100 }];
$scope.selectItem = $scope.ViewItems[0];
$scope.ViewPerPage = 10;
$scope.setitemsPerPage = function (num) {
$scope.ViewPerPage = num.value;
}
//This Section for Modal
$scope.viewObjectives = function (data) {
var modalInstance = $uibModal.open({
templateUrl: '/View/Modal View/OtherObjective.html',
scope: $scope,
size: 'lg',
});
}
function ViewObjective($uibModalInstance, code) {
$scope.id = code;
}
$scope.initial = function () {
var id = $routeParams.id;
if(id!=null)
$scope.viewObjectives(id);
}
$scope.initial();
//PDF Create
$scope.CreatePDF = function () {
$('#objectivelist').tableExport({
type: 'pdf',
fileName: 'ObjectiveList',
jspdf: {
orientation: 'l',
format: 'a4',
margins: { left: 10, right: 10, top: 20, bottom: 20 },
autotable: {
styles: {
fontSize: 10,
fillColor: 'inherit',
textColor: 'inherit'
},
tableWidth: 'auto'
}
}
});
}
}])

Cordova/Ionic httpd server plugin - url not visible

i have a problem with Angular controller in my Ionic/Cordova project.
Can someone explain me why url which i get in line 25: $scope.serverURL=url;
isn't visible in line 63 alert($scope.serverURL); (it return null)?
Here is my controller:
var app = angular.module('iremotee');
app.controller('StreamingController', function(ConnectSdkService, $scope, $rootScope, $state, Camera) {
var options = {
quality: 100,
destinationType: 0,
sourceType: 0,
mediaType: 2
};
$scope.currentFile = null;
$scope.httpd = null;
$scope.serverURL = null;
alert($scope.serverURL + "!!!");
$scope.createHttpd = function() {
$scope.httpd = (cordova && cordova.plugins && cordova.plugins.CorHttpd) ? cordova.plugins.CorHttpd : null;
};
$scope.startMediaServer = function() {
if ($scope.httpd) {
// before start, check whether its up or not
$scope.httpd.getURL(function(url) {
if (url.length > 0) {
$scope.serverURL = url;
alert($scope.serverURL);
} else {
$scope.httpd.startServer({
'www_root': '/',
'port': 8080,
'localhost_only': false
}, function(url) {
$scope.serverURL = url;
alert($scope.serverURL);
}, function(error) {});
}
});
} else {}
};
$scope.stopServer = function() {
if ($scope.httpd) {
$scope.httpd.stopServer(function() {}, function(error) {});
}
};
$scope.getMedia = function() {
$state.go('mainmenu');
};
ionic.Platform.ready(function() {
$scope.createHttpd();
$scope.startMediaServer();
});
$scope.getFile = function() {
alert($scope.serverURL);
Camera.getFromMemory(options).then(function(URI) {
if (URI.indexOf("file://") == -1) {
URI = "file://" + URI;
}
window.resolveLocalFileSystemURL(URI, function(fileEntry) {
var URI = fileEntry.toURL();
var str = URI;
str = str.replace("file:///storage/emulated/0/", "/sdcard/");
str = str.replace("file:///storage/emulated/0/", "/sdcard1/");
str = str.replace("file:///storage", "");
Camera.currentURI = str;
alert(Camera.currentURI);
$scope.currentFile = Camera.currentURI;
}); //resolveLocalFileSystemURL-END
}, function(err) {
alert(err);
}); //getFromMemory-END
}; //getFile-END
$scope.$on('$destroy', function() {
$scope.stopServer();
});
});

Angularjs expression is not working

I tried to use the angular expression below in html 5 but it is not working.
index.html
* * < !DOCTYPE html >
< html >
< script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" > < /script> < script src = "blockuijs.js" > < /script> < body >
< div ng - app = "icebreakerapp" >
< p > My first expression: {
{
5 + 5
}
} </p> </div> < script >
var module = angular.module('icebreakerapp', ['blockUI']); < /script> < /body> < /html>**
blockuijs.js
(function(angular) {
var blkUI = angular.module('blockUI', []);
blkUI.config(["$provide", "$httpProvider", function($provide, $httpProvider) {
$provide.decorator('$exceptionHandler', ['$delegate', '$injector', function($delegate, $injector) {
var blockUI, blockUIConfig;
return function(exception, cause) {
blockUIConfig = blockUIConfig || $injector.get('blockUIConfig');
if (blockUIConfig.resetOnException) {
blockUI = blockUI || $injector.get('blockUI');
blockUI.instances.reset();
}
$delegate(exception, cause);
};
}]);
$httpProvider.interceptors.push('blockUIHttpInterceptor');
}]);
blkUI.run(["$document", "blockUIConfig", "$templateCache", function($document, blockUIConfig, $templateCache) {
if (blockUIConfig.autoInjectBodyBlock) {
$document.find('body').attr('block-ui', 'main');
}
if (blockUIConfig.template) {
blockUIConfig.templateUrl = '$$block-ui-template$$';
$templateCache.put(blockUIConfig.templateUrl, blockUIConfig.template);
}
}]);
blkUI.directive('blockUiContainer', ["blockUIConfig", "blockUiContainerLinkFn", function(blockUIConfig, blockUiContainerLinkFn) {
return {
scope: true,
restrict: 'A',
templateUrl: blockUIConfig.templateUrl,
compile: function($element) {
return blockUiContainerLinkFn;
}
};
}]).factory('blockUiContainerLinkFn', ["blockUI", "blockUIUtils", function(blockUI, blockUIUtils) {
return function($scope, $element, $attrs) {
var srvInstance = $element.inheritedData('block-ui');
if (!srvInstance) {
throw new Error('No parent block-ui service instance located.');
}
$scope.state = srvInstance.state(); //
};
}]);
blkUI.directive('blockUi', ["blockUiCompileFn", function(blockUiCompileFn) {
return {
scope: true,
restrict: 'A',
compile: blockUiCompileFn
};
}]).factory('blockUiCompileFn', ["blockUiPreLinkFn", function(blockUiPreLinkFn) {
return function($element, $attrs) {
$element.append('<div block-ui-container class="block-ui-container"></div>');
return {
pre: blockUiPreLinkFn
};
};
}]).factory('blockUiPreLinkFn', ["blockUI", "blockUIUtils", "blockUIConfig", function(blockUI, blockUIUtils, blockUIConfig) {
return function($scope, $element, $attrs) {
if (!$element.hasClass('block-ui')) {
$element.addClass(blockUIConfig.cssClass);
}
$attrs.$observe('blockUiMessageClass', function(value) {
$scope.$_blockUiMessageClass = value;
});
var instanceId = $attrs.blockUi || '_' + $scope.$id;
var srvInstance = blockUI.instances.get(instanceId);
if (instanceId === 'main') {
var fn = $scope.$on('$viewContentLoaded', function($event) {
fn();
$scope.$on('$locationChangeStart', function(event) {
if (srvInstance.state().blockCount > 0) {
event.preventDefault();
}
});
});
} else {
var parentInstance = $element.inheritedData('block-ui');
if (parentInstance) {
srvInstance._parent = parentInstance;
}
}
$scope.$on('$destroy', function() {
srvInstance.release();
});
srvInstance.addRef();
$scope.$_blockUiState = srvInstance.state();
$scope.$watch('$_blockUiState.blocking', function(value) {
$element.attr('aria-busy', !!value);
$element.toggleClass('block-ui-visible', !!value);
});
$scope.$watch('$_blockUiState.blockCount > 0', function(value) {
$element.toggleClass('block-ui-active', !!value);
});
var pattern = $attrs.blockUiPattern;
if (pattern) {
var regExp = blockUIUtils.buildRegExp(pattern);
srvInstance.pattern(regExp);
}
$element.data('block-ui', srvInstance);
};
}]);
blkUI.constant('blockUIConfig', {
templateUrl: 'angular-block-ui/angular-block-ui.ng.html',
delay: 250,
message: "Loading ...",
autoBlock: true,
resetOnException: true,
requestFilter: angular.noop,
autoInjectBodyBlock: true,
cssClass: 'block-ui block-ui-anim-fade'
});
blkUI.factory('blockUIHttpInterceptor', ["$q", "$injector", "blockUIConfig", function($q, $injector, blockUIConfig) {
var blockUI;
function injectBlockUI() {
blockUI = blockUI || $injector.get('blockUI');
}
function stopBlockUI(config) {
if (blockUIConfig.autoBlock && !config.$_noBlock && config.$_blocks) {
injectBlockUI();
config.$_blocks.stop();
}
}
function error(rejection) {
stopBlockUI(rejection.config);
return $q.reject(rejection);
}
return {
request: function(config) {
if (blockUIConfig.autoBlock) {
if (blockUIConfig.requestFilter(config) === false) {
config.$_noBlock = true;
} else {
injectBlockUI();
config.$_blocks = blockUI.instances.locate(config);
config.$_blocks.start();
}
}
return config;
},
requestError: error,
response: function(response) {
stopBlockUI(response.config);
return response;
},
responseError: error
};
}]);
blkUI.factory('blockUI', ["blockUIConfig", "$timeout", "blockUIUtils", "$document", function(blockUIConfig, $timeout, blockUIUtils, $document) {
var $body = $document.find('body');
function BlockUI(id) {
var self = this;
var state = {
id: id,
blockCount: 0,
message: blockUIConfig.message,
blocking: false
},
startPromise, doneCallbacks = [];
this._refs = 0;
this.start = function(message) {
if (state.blockCount > 0) {
message = message || state.message || blockUIConfig.message;
} else {
message = message || blockUIConfig.message;
}
state.message = message;
state.blockCount++;
var $ae = angular.element($document[0].activeElement);
if ($ae.length && blockUIUtils.isElementInBlockScope($ae, self)) { //
self._restoreFocus = $ae[0];
$timeout(function() {
if (self._restoreFocus) {
self._restoreFocus.blur();
}
});
}
if (!startPromise) {
startPromise = $timeout(function() {
startPromise = null;
state.blocking = true;
}, blockUIConfig.delay);
}
};
this._cancelStartTimeout = function() {
if (startPromise) {
$timeout.cancel(startPromise);
startPromise = null;
}
};
this.stop = function() {
state.blockCount = Math.max(0, --state.blockCount);
if (state.blockCount === 0) {
self.reset(true);
}
};
this.message = function(value) {
state.message = value;
};
this.pattern = function(regexp) {
if (regexp !== undefined) {
self._pattern = regexp;
}
return self._pattern;
};
this.reset = function(executeCallbacks) {
self._cancelStartTimeout();
state.blockCount = 0;
state.blocking = false;
if (self._restoreFocus && (!$document[0].activeElement || $document[0].activeElement === $body[0])) {
self._restoreFocus.focus();
self._restoreFocus = null;
}
try {
if (executeCallbacks) {
angular.forEach(doneCallbacks, function(cb) {
cb();
});
}
} finally {
doneCallbacks.length = 0;
}
};
this.done = function(fn) {
doneCallbacks.push(fn);
};
this.state = function() {
return state;
};
this.addRef = function() {
self._refs += 1;
};
this.release = function() {
if (--self._refs <= 0) {
mainBlock.instances._destroy(self);
}
};
}
var instances = [];
instances.get = function(id) {
var instance = instances[id];
if (!instance) {
instance = instances[id] = new BlockUI(id);
instances.push(instance);
}
return instance;
};
instances._destroy = function(idOrInstance) {
if (angular.isString(idOrInstance)) {
idOrInstance = instances[idOrInstance];
}
if (idOrInstance) {
idOrInstance.reset();
delete instances[idOrInstance.state().id];
var i = instances.length;
while (--i) {
if (instances[i] === idOrInstance) {
instances.splice(i, 1);
break;
}
}
}
};
instances.locate = function(request) {
var result = [];
blockUIUtils.forEachFnHook(result, 'start');
blockUIUtils.forEachFnHook(result, 'stop');
var i = instances.length;
while (i--) {
var instance = instances[i];
var pattern = instance._pattern;
if (pattern && pattern.test(request.url)) {
result.push(instance);
}
}
if (result.length === 0) {
result.push(mainBlock);
}
return result;
};
blockUIUtils.forEachFnHook(instances, 'reset');
var mainBlock = instances.get('main');
mainBlock.addRef();
mainBlock.instances = instances;
return mainBlock;
}]);
blkUI.factory('blockUIUtils', function() {
var $ = angular.element;
var utils = {
buildRegExp: function(pattern) {
var match = pattern.match(/^\/(.*)\/([gim]*)$/),
regExp;
if (match) {
regExp = new RegExp(match[1], match[2]);
} else {
throw Error('Incorrect regular expression format: ' + pattern);
}
return regExp;
},
forEachFn: function(arr, fnName, args) {
var i = arr.length;
while (i--) {
var t = arr[i];
t[fnName].apply(t, args);
}
},
forEachFnHook: function(arr, fnName) {
arr[fnName] = function() {
utils.forEachFn(this, fnName, arguments);
}
},
isElementInBlockScope: function($element, blockScope) {
var c = $element.inheritedData('block-ui');
while (c) {
if (c === blockScope) {
return true;
}
c = c._parent;
}
return false;
},
findElement: function($element, predicateFn, traverse) {
var ret = null;
if (predicateFn($element)) {
ret = $element;
} else {
var $elements;
if (traverse) {
$elements = $element.parent();
} else {
$elements = $element.children();
}
var i = $elements.length;
while (!ret && i--) {
ret = utils.findElement($($elements[i]), predicateFn, traverse);
}
}
return ret;
}
};
return utils;
});
angular.module('blockUI').run(['$templateCache', function($templateCache) {
$templateCache.put('angular-block-ui/angular-block-ui.ng.html', '<div class=\"block-ui-overlay\"></div><div class=\"block-ui-message-container\" aria-live=\"assertive\" aria-atomic=\"true\"><div class=\"block-ui-message loading_spinnerlatest\" ng-class=\"$_blockUiMessageClass\">{{ state.message }}</div></div>');
}]);
})(angular); //
It is giving the output as "My first expression:{{ 5+5}}".But expectation is "My first expression:10"
Note: If I remove dependency modules in (angular.module) it is working.But I need those dependency modules
for further development
Are you seeing any error in console? Maybe some of your module dependencies are not resolved.
Check this snippet:
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="icebreakerapp">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
<script>
var module = angular.module('icebreakerapp', []);
</script>

set the data from controller into directive

I had created the directive file like this:
angular.module('myApp')
.directive('rGraph', function() {
return {
link: function ( scope, element, attrs ) {
var width = Math.max($("#graph-container").innerWidth(), 400);
var height = Math.max(width, 550);
var rgraph = new $jit.RGraph({
injectInto: 'graphcontainer',
width: width,
height: height,
background: {
CanvasStyles: {
strokeStyle: '#555'
}
},
Navigation: {
enable: true,
panning: true,
zooming: 10
},
Node: {
color: '#ddeeff',
overridable: true
},
Edge: {
color: '#C17878',
lineWidth: 1.0
},
onCreateLabel: function(domElement, node){
domElement.innerHTML = node.name;
domElement.onclick = function(){
rgraph.onClick(node.id, {
onComplete: function() {
Log.write("done");
}
});
};
},
onPlaceLabel: function(domElement, node){
style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#ccc";
} else if(node._depth == 2){
style.fontSize = "0.7em";
style.color = "#494949";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onBeforePlotNode: function(node){
if (node.data.type == 'group') {
node.setData('type', 'square');
} else if (node.data.type == 'judge') {
node.setData('type', 'star');
node.setData('dim', '8');
}
}
});
//Here I need to set the data
rgraph.loadJSON();
rgraph.refresh();
// Completing animations on every change was too much
// TODO come up with better way to watch for changes
rgraph.graph.eachNode(function(n) {
var pos = n.getPos();
pos.setc(-200, -200);
});
rgraph.compute('end');
rgraph.fx.animate({
modes:['polar'],
duration: 2000
});
}
};
});
And my controller is like this:
angular.module('myApp').controller('AnalysisCtrl', ['$scope', '$http', '$q', 'SearchService', function($scope, $http, $q, SearchService) {
$scope.graph_data = {
'id': 'judge_id',
'name': judge.name,
'type': 'judge',
'children': filters
}
My view is where I ma calling directive is like this:
<div id="graphcontainer" r-graph="graph_data"></div>
Now i need to add the data get from controller i.e data of $scope.graph_data into to the rgraph.loadJSON(); of directives.So how to do that.
Thanks
Sabbu

Resources