angular.module("modalApp", ['ngAnimate', "ngMaterial", "ngMessages"])
.controller('modalCtrl', function ($scope) {
$scope.direction = 'left';
$scope.currentIndex = 0;
$scope.init = true;
$scope.initWizard = function() {
if($scope.init) {
$scope.setCurrentIndex(0);
}
$scope.init = false;
}
$scope.setCurrentIndex = function (index) {
$scope.currentIndex = index;
}
$scope.isCurrentIndex = function (index) {
return $scope.currentIndex === index;
}
$scope.nextModalStep = function () {
$scope.direction = 'left';
if($scope.currentIndex < $scope.modalSteps.length - 1) {
++$scope.currentIndex;
}
}
$scope.prevModalStep = function () {
$scope.direction = 'right';
if($scope.currentIndex > 0) {
--$scope.currentIndex;
}
}
})
.animation('.modalViewAnimation', function () {
return {
beforeAddClass: function(element, className, done) {
var scope = element.scope();
if (className == 'ng-hide') {
var elementWidth = element.parent().width();
startPoint = 0;
if(scope.direction !== "right") {
finishPoint = elementWidth;
} else {
finishPoint = -elementWidth;
}
TweenMax.fromTo(element, 0.5, { left: startPoint}, {x: finishPoint, onComplete: done });
} else {
done();
}
},
removeClass: function(element, className, done) {
var scope = element.scope();
if (className == 'ng-hide') {
var elementWidth = element.parent().width();
finishPoint = 0;
if(scope.direction !== "right") {
startPoint = elementWidth;
} else {
startPoint = -elementWidth;
}
TweenMax.to("section", 0.5, { height: element.outerHeight()});
TweenMax.fromTo(element, 0.5, { x: startPoint}, {x: finishPoint, onComplete: done, delay:0.25});
} else {
done();
}
}
}
});
I have a wizard slider that is almost working. My problem is accessing the direction property in my animation function after it has been set in the controller. The scope object has value inside the animation but the dot notation of retrieving the direction property with "scope.direction" returns undefined. Why? Any help greatly appreciated. Worth mentioning, I modified the animation function ever so slightly from this https://github.com/simpulton/angular-photo-slider to achieve what I want. I can't see why my scope.direction returns undefined?
Not sure the reason, but I had to get it from childHead.
The key for me was injecting rootScope.
Working example: JSFiddle
(edited to 'tidy' my code ;-) )
var myApp = angular.module('myApp', ['ngAnimate']);
myApp.controller('myCtrl', function($scope) {
$scope.onOff = false;
});
myApp.animation('.fold-animation-expand', ['$animateCss', '$rootScope',
function($animateCss, $rootScope) {
return {
enter: function(element, doneFn) {
console.log("onOff:" + $rootScope.$$childHead.onOff);
return $animateCss(element, {
from: {
"font-size": '0px'
},
to: {
"font-size": '20px'
},
duration: 2
});
}
}
}
]);
.box {
height: 100px;
width: 100px;
background-color: blue;
color: white;
float: left;
}
.box.ng-enter {
transition: 2s linear all;
opacity: 0;
}
.box.ng-enter.ng-enter-active {
opacity: 1;
}
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-2.2.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0/angular-animate.js"></script>
</head>
<body>
<div ng-controller='myCtrl'>
onOff state:{{onOff}}
<br>
<br>
<button ng-click="onOff?onOff=false:onOff=true">Run animation</button>
<hr>
<div ng-if="onOff == true" class="fold-animation-expand" style="font-size:0px">
Expanding element
</div>
<hr>Example of CSS-based transition
<br>
<div ng-if="onOff" class="box">Animated Box</div>
</div>
</body>
</html>
Related
Trying to get selected clicked image to expand in a gallery of images. I have the expanding working but it only works on the first image in the sets. If I click on another image in the set the first one is the one that gets expanded
<div ng-repeat="album in albumData|filter:q" id="thumbWrapper">
<h1>{{album.id}}</h1>
<h2 ng-click="showme = !showme">{{album.title}}</h2>
<div id="thumbList"ng-show="showme"class="albumContent">
<ul ng-controller="PhotoCtrl" id="thumbList">
<li ng-repeat="photo in photoData" ng-if="album.userId == photo.albumId">
<img id="view" ng-click="zoom()" ng-src={{photo.url}}>
</li>
</ul>
</div>
</div>
</div>
here's my angular js code
var app = angular.module('myApp', []);
app.controller('AlbumCtrl', function ($scope, $http) {
$http.get("http://jsonplaceholder.typicode.com/albums").then(function(response) {
$scope.albumData = response.data;
console.log($scope.albumData);
});
});
app.controller('PhotoCtrl', function($scope, $http) {
$http.get("http://jsonplaceholder.typicode.com/photos").then(function(response) {
$scope.photoData = response.data;
$scope.zoom = function() {
var imageId = document.getElementById('view');
if(imageId.style.width == "1000px"){
imageId.style.width = "600px";
imageId.style.height = "600px";
}else{
imageId.style.width = "1000px";
imageId.style.height = "1000px";
}
};
// console.log($scope.photoData);
});
});
any help would be awesome!
make the image id unique for each img tag
<img id="view{{$index}}" ng-click="zoom($index)" ng-src={{photo.url}}>
pass the index as parameter to the function
$scope.zoom = function(index) {
var elem = "view" + index;
var imageId = document.getElementById(elem);
if (imageId.style.width == "1000px") {
imageId.style.width = "600px";
imageId.style.height = "600px";
} else {
imageId.style.width = "1000px";
}
}
and put the zoom function out side of the http request
You can try this directory. Just copy and paste this code in the app.js and css code in style.css. But be careful, this applies to all images in your website
.directive('img', function ($window) {
'use strict';
function getElementOffset (element) {
var de = document.documentElement;
var box = element.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
}
return {
restrict: 'E',
link: function (scope, element, attr) {
var expanded = false,
cloned = element.clone(true),
offset = getElementOffset(element[0]);
cloned.addClass('large');
cloned.attr('src', attr.src);
cloned.css('top', offset.top + 'px');
cloned.css('left', offset.left + 'px');
cloned.bind('click', function () {
if (expanded) {
cloned.removeClass('expanded');
expanded = false;
} else {
cloned.addClass('expanded');
expanded = true;
}
});
element.parent().append(cloned);
angular.element($window).bind('scroll', function () {
if (expanded) {
cloned.removeClass('expanded');
expanded = false;
}
});
}
};
});
CSS:
.app img {
display: block;
float: right;
width: 200px;
}
.app img.large {
cursor: -moz-zoom-in;
cursor: -webkit-zoom-in;
cursor: zoom-in;
position: absolute;
-webkit-transition: all 0.25s ease-out;
transition: all 0.25s ease-out;
}
.app img.expanded {
cursor: -moz-zoom-out;
cursor: -webkit-zoom-out;
cursor: zoom-out;
left: 0 !important;
top: 0 !important;
width: 100%;
}
source: https://jsfiddle.net/kmturley/jwtj57kt/
I had created a angular audio app. i want to display play list in it . Using directive to trigger play pause and other operations. Please help me to create play list here.
my main html is
<!DOCTYPE html>
<html ng-app="app">
<head>
<title> AUDIO</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="css/ng-cool-audio.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="js/ng-cool-audio.js"></script>
<script src="js/app.js"></script>
<style>
body {
background-color: #f5f5f5;
font-family: Helvetica Neue, Helvetica, arial, sans-serif;
}
.main {
width: 800px;
margin: 100px auto;
}
</style>
</head>
<body ng-controller="MainCtrl">
<div class="main">
<ng-cool-audio source="source2"></ng-cool-audio>
</div>
</body>
</html>
my html template is
<div class="ng-cool-audio-container">
<audio>
Your browser seems to be upgraded! :)
</audio>
<div class="ng-cool-audio-preview">
<div class="ncv-audio-left">
<div class="ncv-img-container">
<img ng-src="{{audio.cover}}" alt="Photo">
</div>
</div>
<div class="ncv-audio-right">
<div class="ncv-audio-right-top">
<div class="ncv-header">
<div class="ncv-header-title">{{audio.author}}</div>
<div class="ncv-header-subtitle">{{audio.name}}</div>
<div class="ncv-audio-sound">
<i class="fa fa-volume-up" ng-show="!isMuted" ng-click="volumeOff()"></i>
<i class="fa fa-volume-off" ng-show="isMuted" ng-click="volumeOn()"></i>
<input type="range" max="10" min="0" value="5">
</div>
</div>
</div>
<div class="ncv-audio-right-bottom">
<div class="ncv-audio-controls">
<i class="fa fa-backward" ng-click="playBackward()"></i>
<i class="fa fa-play" ng-click="play()"></i>
<i class="fa fa-pause" ng-click="pause()"></i>
<i class="fa fa-forward" ng-click="playForward()"></i>
</div>
<div class="ncv-progress">
<progress class="ncv-progress-bar" max="100" value="{{progressValue}}"></progress>
</div>
<div class="ncv-time">
<span class="ncv-current-time">{{currentTime}}</span>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
<h4> PLAY LIST </h4>
<div class="col-lg-3" ng-repeat="song in source2">
{{song.audio.name}}
</div>
</div>
</div>
app.js is
(function() {
'use strict';
angular
.module('app', [
'ngCoolAudio'
])
.controller('MainCtrl', function($scope) {
$scope.source2 = {
audio: [{
author: 'Dr. SPB',
cover: 'images/about.jpg',
src: 'audio/AADI ANAADI-SPB.mp3',
name: 'AADI ANAADI'
},
{
author: 'Dr.RAJ',
cover: 'images/about.jpg',
src: 'audio/BHAVA SAAGARADA AALADI-DR.RAJ.mp3',
name: 'BHAVA SAAGARADA AALADI'
},
{
author: 'Dr.RAJ',
cover: 'images/about.jpg',
src: 'audio/CHARAKULAAMBUDHI CHANDIRA-DR.RAJ (2).mp3',
name: 'CHARAKULAAMBUDHI CHANDIRA'
},
{
author: 'S.JANAKI',
cover: 'images/about.jpg',
src: 'audio/DHYANA MAADUTHIRU-S.JANAKI .mp3',
name: 'DHYANA MAADUTHIRU'
},
{
author: 'OM',
cover: 'images/about.jpg',
src: 'audio/Om Namahshivaya.mp3',
name: 'OM NAMAHSHIVAYA'
}
],
config: {
autoplay: false,
loop: true
}
}
})
})();
audio directive is
(function() {
'use strict';
angular
.module('ngCoolAudio', [])
.directive('ngCoolAudio', [
'$timeout',
'$sce',
function($timeout, $sce) {
return {
restrict: 'AE',
scope: {
source: '=source'
},
replace: true,
templateUrl: 'html/audio.html',
controller: ['$scope', '$element', function($scope, $element) {
//check source file
if (!$scope.source || !$scope.source.audio) {
throw new Error('Source seems not to config right!');
return;
}
var container = $element[0].querySelector('.ng-cool-audio-container');
var audio = $element[0].querySelector('audio');
var volume_range = $element[0].querySelector('.ncv-audio-sound input[type="range"]');
var $audio = angular.element(audio);
$scope.audio = {};
//private method
var calCulateTime = function() {
var secs = parseInt(audio.currentTime % 60);
var mins = parseInt((audio.currentTime / 60) % 60);
// Ensure it's two digits. For example, 03 rather than 3.
secs = ("0" + secs).slice(-2);
mins = ("0" + mins).slice(-2);
return mins + ':' + secs;
}
var calCulateProgress = function() {
var percent = (100 / audio.duration) * audio.currentTime;
return percent;
}
var generateAudio = function(audio) {
if (!audio.src) {
throw new Error('Not found src in your audio config');
return;
}
$audio.attr('src', audio.src);
$scope.audio.cover = audio.cover || 'http://7xj610.com1.z0.glb.clouddn.com/29ce98b4349b72c2778d2f82823159b06f98f8bc.jpeg';
$scope.audio.author = audio.author || 'Unknow';
$scope.audio.name = audio.name || 'Unknow';
}
$scope.currentTrack = 0;
$scope.jumpInterval = 10;
$scope.init = function() {
$scope.currentTime = '00:00';
$scope.progressValue = 0;
$scope.isPlaying = false;
$scope.isMuted = false;
$scope.setInterface($scope.currentTrack);
$scope.addEvents();
};
$scope.setInterface = function(index) {
var isArray = angular.isArray($scope.source.audio);
if (isArray) {
$scope.audioCollection = $scope.source.audio;
generateAudio($scope.audioCollection[index]);
} else {
generateAudio($scope.source.audio);
}
if ($scope.source.config) {
if ($scope.source.config.autoplay) {
$audio.attr('autoplay', 'autoplay');
$scope.play();
}
if ($scope.source.config.loop) {
$audio.attr('loop', 'loop');
}
}
};
//toggle play pause
$scope.play = function() {
audio.play();
$scope.isPlaying = true;
};
$scope.pause = function() {
audio.pause();
$scope.isPlaying = false;
};
//toggle mute
$scope.volumeOn = function() {
audio.muted = false;
$scope.isMuted = false;
};
$scope.volumeOff = function() {
audio.muted = true;
$scope.isMuted = true;
};
//backward forward
$scope.playBackward = function() {
//here jump to pre song
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.currentTrack -= 1;
if ($scope.currentTrack < 0) {
$scope.currentTrack = $scope.audioCollection.length - 1;
}
$scope.init();
$scope.play();
} else {
var toTime = audio.currentTime - $scope.jumpInterval;
if (toTime < 0) {
audio.currentTime = 0;
} else {
audio.currentTime = toTime;
}
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
};
$scope.playForward = function() {
//here jump to next song
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.currentTrack += 1;
if ($scope.currentTrack > $scope.audioCollection.length - 1) {
$scope.currentTrack = 0;
}
$scope.init();
$scope.play();
} else {
var toTime = audio.currentTime + $scope.jumpInterval;
if (toTime > audio.duration) {
audio.currentTime = audio.duration;
} else {
audio.currentTime = toTime;
}
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
};
//skip progress
$scope.skipProgress = function(e) {
//update time and progress
var target = e.target;
var offsetX = 0;
if (!e.pageX || !target.offsetLeft) {
offsetX = e.offsetX ? e.offsetX : e.layerX;
} else {
offsetX = e.pageX - target.offsetLeft;
}
var pos = offsetX / target.offsetWidth;
audio.currentTime = pos * audio.duration;
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
$scope.addEvents = function() {
//time update
// progress update
audio.addEventListener('timeupdate', function() {
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
$scope.$apply();
}, false);
audio.addEventListener('ended', function() {
//auto play next
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.playForward();
}
});
//angular seems dont support input[range] stuff so let's do it event
volume_range.addEventListener('change', function() {
audio.volume = parseFloat(this.value / 10);
}, false);
}
}],
link: function(scope, ele, attrs) {
scope.init();
}
}
}
])
})();
i have seven div tags each
<div style="width:200px;height:100px" ng-controller="civCntlr">
You can use $rootScope.$broadcast + $rootScope.$on to communicate between controllers. For example,
var commApp = angular.module('CommApp', []);
commApp.controller('firstDivController', function($scope, $rootScope) {
$scope.class = "blue";
$scope.click = function() {
$rootScope.$broadcast("selected", "blue");
if ($scope.class === "blue") {
$scope.class = "active";
}
};
$rootScope.$on('selected', function(event, data) {
if (data !== "blue")
$scope.class = "blue";
});
});
commApp.controller('secDivController', function($scope, $rootScope) {
$scope.class = "green"
$scope.click = function() {
$rootScope.$broadcast("selected", "green");
if ($scope.class === "green") {
$scope.class = "active";
}
};
$rootScope.$on('selected', function(event, data) {
if (data !== "green")
$scope.class = "green";
});
});
commApp.controller('thirdDivController', function($scope, $rootScope) {
$scope.class = "red"
$scope.click = function() {
$rootScope.$broadcast("selected", "red");
if ($scope.class === "red") {
$scope.class = "active";
}
};
$rootScope.$on('selected', function(event, data) {
if (data !== "red")
$scope.class = "red";
});
});
commApp.controller('lastDivController', function($scope, $rootScope) {
$scope.class = "black"
$scope.click = function() {
$rootScope.$broadcast("selected", "black");
if ($scope.class === "black") {
$scope.class = "active";
}
};
$rootScope.$on('selected', function(event, data) {
if (data !== "black")
$scope.class = "black";
});
});
You can broadcast and listen on every controller like above.
However, just applying class is only your requirement, you can add and remove class dynamically.
$scope.click = function() {
angular.element(document.getElementsByClassName('active')).removeClass('active');
angular.element(document.getElementsByClassName('blue')).addClass('active');
};
It is always good to use service to communicate between controllers. I have done a small demo to show how to communicate between controllers using a service.
When ever data/some flag is changed then save it to the service. Your service should broadcast the changes to all the controllers. You then get the data from the service and change the view accordingly.
angular.module('myApp', []);
angular.module('myApp').controller('firstDivController', function($scope, service) {
$scope.divColor = (service.getId() == 'one' ? "green" : "red");
$scope.click = function() {
alert('Ctrl One');
service.setId('one');
};
$scope.$on('id', function() {
$scope.divColor = (service.getId() == 'one' ? "green" : "red");
});
});
angular.module('myApp').controller('secDivController', function($scope, service) {
$scope.divColor = (service.getId() == 'two' ? "green" : "red");
$scope.click = function() {
alert('Ctrl two');
service.setId('two');
};
$scope.$on('id', function() {
$scope.divColor = (service.getId() == 'two' ? "green" : "red");
});
});
angular.module('myApp').service('service', function($rootScope) {
var divId = 'one';
this.getId = function() {
return divId;
};
this.setId = function(id) {
divId = id;
this.broadcastId();
};
this.broadcastId = function() {
$rootScope.$broadcast('id');
};
});
Update:
After suggestion from #Cyril Gandon I have updated the code by removing the broadcast.
Working Plunker
Use ng-style and then use condition (ternary operator) inside ng-style
You should use a service when you need controller communicating.
Read this article on anti-patterns:
Only use .$broadcast(), .$emit() and .$on() for atomic events
Events that are relevant globally across the entire app (such as a user authenticating or the app closing). If you want events specific to modules, services or widgets you should consider Services, Directive Controllers, or 3rd Party Libs
$scope.$watch() should replace the need for events
Injecting services and calling methods directly is also useful for direct communication
Directives are able to directly communicate with each other through directive-controllers
// Code goes here
angular.module('myApp', []);
angular.module('myApp').service('activeService', function($rootScope) {
var activeId = 'one';
this.isActive = function(id) {
return activeId == id;
};
this.setActive = function(id) {
activeId = id;
};
});
angular.module('myApp').controller('firstDivController', function($scope, activeService) {
var id = 'one';
$scope.click = function() {
activeService.setActive(id);
};
$scope.getDivColor = function() {
return activeService.isActive(id) ? 'active' : 'blue';
};
});
angular.module('myApp').controller('secDivController', function($scope, activeService) {
var id = 'two';
$scope.click = function() {
activeService.setActive(id);
};
$scope.getDivColor = function() {
return activeService.isActive(id) ? 'active' : 'green';
};
});
angular.module('myApp').controller('thirdDivController', function($scope, activeService) {
var id = 'three';
$scope.click = function() {
activeService.setActive(id);
};
$scope.getDivColor = function() {
return activeService.isActive(id) ? 'active' : 'red';
};
});
angular.module('myApp').controller('lastDivController', function($scope, activeService) {
var id = 'last';
$scope.click = function() {
activeService.setActive(id);
};
$scope.getDivColor = function() {
return activeService.isActive(id) ? 'active' : 'black';
};
});
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.black {
background-color: black;
}
.active{
background-color: yellow ;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
</head>
<body>
<div style="width:200px;height:30px"
ng-controller="firstDivController"
ng-click="click()"
ng-class="getDivColor()">
<center>Hello , your in first box</center>
</div>
<div style="width:200px;height:30px"
ng-controller="secDivController"
ng-click="click()"
ng-class="getDivColor()">
<center>Hello , you are in second box</center>
</div>
<div style="width:200px;height:30px"
ng-controller="thirdDivController"
ng-click="click()"
ng-class="getDivColor()">
<center>Hello , you are in third box</center>
</div>
<div style="width:200px;height:30px"
ng-controller="lastDivController"
ng-click="click()"
ng-class="getDivColor()">
<center>Hello , you are in last box</center>
</div>
</body>
</html>
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);
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