set the data from controller into directive - angularjs

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

Related

ui-calendar cell background color not displaying for the first time

I am trying to get a list of dates from Rest and change the background color of those dates using dayRender .But when i try to do it the color is not getting changed for the first time.If i go to next month and come back to the month,it will work perfectly.Here are screenshots to make it more clear.
When i load the page
When i move from june to july
When move back to june
Here is my code .rest/leave/holidayList is the rest url for retreiving dates from db.
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error");
});
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate=moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function (date, cell) {
var today = new Date();
today=moment(today).toDate();
var end = new Date();
end=moment(end).toDate();
end.setDate(today.getDate()+7);
date=moment(date).toDate();
angular.forEach($scope.holidayList,function(value){
if(((moment(value.holiday_date).format("YYYY-MM-DD"))==moment(date).format("YYYY-MM-DD")))
{
cell.css("background-color", "red");
}
});
},
eventRender: $scope.eventRender,
}
};
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
Remember that the REST call is asynchronous. Just put all the code that set colours inside a promise, so when the REST service rest/leave/holidayList responses, then you paint the colours. You can use nested promises if needed.
Here's some code:
$http.get('rest/leave/holidayList').then(function(response) {
// success
$scope.holidayList = data;
/* config object */
$scope.uiConfig = {
calendar: {
/* calendar code */
}
}
}, function(response) {
// error handler
});
To compare the use of "success" and "then" have a look at:
https://stackoverflow.com/a/16385350/8058079

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'
}
}
});
}
}])

How to redraw flot chart in angularjs?

I am using flot chart Angularjs directive to draw a stacked bar chart. When I make a async call to an end point to fetch data for chart, it is unable show up. I suspect it needs to redraw. There is a draw() function which looks like re draws flot chart. Please help me re-draw my flot chart in Angularjs.
<flot dataset="tasksRunData" options="tasksRunChartOptions" class="center-block" width="100%" height="400px" id="reportTasksRunRange.id"></flot>
angular.module('myApp').controller('Step2Controller', function($scope, $location, $interval, dialogs, $modal, $transition, ReportingService) {
...
$scope.tasksRunData = mainArray;
$scope.tasksRunChartOptions = {
legend: {
show: true,
margin: 2
},
xaxis: {
ticks: yaxisArray,
alignTicksWithAxis: "right"
},
grid: {
labelMargin: 10,
hoverable: true,
borderWidth: 0
},
series: {
stack: true
},
colors: colorCodesArray,
tooltip: true
};
...
$scope.redrawTasksRunDataHistoByChart();
...
$scope.redrawTasksRunDataHistoByChart = function() {
$scope.tasksRunData.draw(); //TypeError: undefined is not a function
alert("AAAA");
}
});
Update
ReportService.getTasksRunDateHistoByType().then(function(result) {
$scope.renderTasksRunDateHistoByType(result);
});
$scope.renderTasksRunDateHistoByType = function(jsonInput) {
console.log(json[RUN_AGG_BY_DATE_HISTO].aggregations[TASK_TYPE_AGG].buckets);
var yaxis = [];
var buckets = json[RUN_AGG_BY_DATE_HISTO].aggregations[TASK_TYPE_AGG].buckets;
var log = [];
var mainArray = [];
var colorCodes = ["#5C832F","#7B52AB","#263248","#AB1A25","#FF8598","#AB1A25","#FEB41C","#193441","#193441","#BEEB9F","#E3DB9A","#917A56"],
idx = 0;
angular.forEach(buckets, function(value, key) {
this.push(key + ': ' + value +", "+value["key"]);
var dataArray = [], index = 0;
console.log(JSON.stringify(value[RUN_OVER_TIME_KEY]["buckets"]));
angular.forEach(value[RUN_OVER_TIME_KEY]["buckets"], function(value, key) {
var dataArr = [];
dataArr.push('['+index+', '+value["doc_count"]+']');
dataArray.push(dataArr);
yaxis.push(JSON.parse('['+index+', "'+$scope.translate(value["key"])+'", "'+value["key"]+'"]'));
index++;
}, log);
var barObject = '"bars": {"show": "true", "barWidth":0.8, "fillColor": "'+colorCodes[idx]+'", "order": 1, "align": "center"}';
var object = '{ "data": ['+dataArray+'], "label": "'+value["key"]+'", '+barObject+'}';
mainArray.push(JSON.parse(object));
idx++;
}, log);
console.log(yaxis);
$scope.tasksRunData = mainArray;
$scope.tasksRunChartOptions = {
legend: {
show: true,
margin: 2
},
xaxis: {
//ticks:[[0,'Oct 4'],[1,'Oct 5'],[2,'Oct 6'],[3,'Oct 7'],[4,'Oct 8'],[5,'Oct 9']],
ticks: yaxis,
alignTicksWithAxis: "right"
},
grid: {
labelMargin: 10,
hoverable: true,
borderWidth: 0
},
series: {
stack: true
},
colors: colorCodes,
tooltip: true
};
};
angularjs service
angular.module('myApp')
.service('ReportService', function ReportService($http, $q) {
var getTasksRunDateHistoByType = function() {
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://localhost:4040/reports/taskRun",
data: '{ "client_user_info": { "client_id": "MU03"}}'
}).
success(function(result, status, headers, config) {
deferred.resolve(result);
}).
error(function(result, status, headers, config) {
console.log("Error");
});
return deferred.promise;
};
return {
getTasksRunDateHistoByType: getTasksRunDateHistoByType
};
});
Looking at the source code to the directive, it'll redraw automatically when $scope.dataset changes.
$scope.redrawChart = function() {
var tmp = [];
for (var i = 0; i < 10; i++){
tmp.push([i,Math.random() * 10]);
}
$scope.dataset = [{ data: tmp }];
};
Here's an example.
EDITS FOR UPDATES
I'm having a hard time following your code, but in the end, you'll end up in the $scope.renderTasksRunDateHistoByType with data in the variable jsonInput. You then store some variable mainArray (which doesn't exist as far as I can tell) into other $scope level variables. I never see you assign data back to $scope.dataset. This is what the flot directive is watching to trigger a redraw. It's just that simple.
$scope.renderTasksRunDateHistoByType = function(jsonInput) {
$scope.dataset = [{
data: jsonInput
}];
//console.log(jsonInput);
//$scope.tasksRunData = mainArray;
//$scope.tasksRunChartOptions
//getting data here once response is received from server
};
See updates here.

AngularJS: window service and directive

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);

Resources