recently I really like Google I/O 2015 event page, especially those transition animations between different states. I know they used Polymer for that, but I'm trying to recreate such delayed animations in Angular (1.4.1) and Angular-material and ui-router.
Basically what I want to achieve is this workflow:
before state change, animate leaving components of the app
leave some basic structure of the app (some basic holder containers)
make state change - resolve resources (REST API call)
transition to new state, with basic app structure (holders)
animate entering elements (with different delays)
This is not trivial task, and ng-animate is not very helpful, but I want to use is as much as possible. One drawback is, that leaving css classes are not added, before promises are resolved, the other it, that at one moment, both - old and new state view are present on the page.
I tried to create this directive:
(function() {
'use strict';
angular
.module('climbguide')
.directive('cgAnimateElement', cgAnimateElement);
/* #ngInject */
function cgAnimateElement($animate, $rootScope, $state) {
return {
restrict: 'A',
link: linkFunc
};
function linkFunc(scope, el) {
$animate.enter(el, el.parent());
var cleanUp = $rootScope.$on('$stateChangeStart',
function(event, toState, toParams) {
if ($rootScope.stateChangeBypass) {
$rootScope.stateChangeBypass = false;
return;
}
event.preventDefault();
var promise = $animate.leave(el);
promise.then(function() {
$rootScope.stateChangeBypass = true;
$state.go(toState.name, toParams);
});
});
scope.$on('$destroy', function() {
cleanUp();
});
}
}
})();
It basically does what I want, however for some reason it is only possible to use it one element - I assume because of the $rootScope.$on('$stateChangeStart') and later use of $state.go(toState.name, toParams);.
I also found two other solutions,
angular-ui-router-in-out, which uses CSS, but there is waiting for promises to be resolved before any animation happens (the loader animation would be necessary)
angular-gsapify-router, which uses javascript animations, and has the same problem as above one.
I'm still only learning angular, so I really don't know how to do this in a right way. Do you have any ideas? Thanks a lot.
P.S.: sorry for missing links to the libraries, but this is my first post to SO, so I can only post 2 links :)
Maybe it will help somebody, but I got it to work with probably dirty hack, but anyway it does, what I described in the original post.
I changed the directive so it can be re-used more times:
(function() {
'use strict';
angular
.module('climbguide')
.directive('cgAnimateElement', cgAnimateElement);
/* #ngInject */
function cgAnimateElement($animate, delayedRouterService) {
return {
restrict: 'A',
link: linkFunc
};
function linkFunc(scope, el) {
var stateChangeBypass = false;
$animate.enter(el, el.parent());
// Use scope instead of $rootScope, so there is no need to de-register listener
scope.$on('$stateChangeStart',
function(event, toState, toParams) {
if (stateChangeBypass) {
// Resuming transition to the next state broadcasts new $stateChangeStart
// event, so it necessary to bypass it
stateChangeBypass = false;
return;
}
delayedRouterService.holdStateChange(event);
var promise = $animate.leave(el);
promise.then(function() {
stateChangeBypass = true;
delayedRouterService.releaseStateChange(toState, toParams);
});
});
}
}
})();
I created service for handling state changes - preventing and resuming state changes in ui-router:
(function() {
'use strict';
angular
.module('climbguide')
.factory('delayedRouterService', delayedRouterService);
/* #ngInject */
function delayedRouterService($state) {
var _runningAnimations = 0;
/**
* Public methods
*
*/
var service = {
holdStateChange: holdStateChange,
releaseStateChange: releaseStateChange
};
return service;
//////////////
/**
* Prevent state change from the first animation
* Store the number of currently running animations
*
* #param event
*/
function holdStateChange(event) {
if (_runningAnimations === 0) {
event.preventDefault();
}
_runningAnimations++;
}
/**
* Remove animation from the stack after it is finished
* Resume state transition after last animation is finished
*
* #param toState
* #param toParams
*/
function releaseStateChange(toState, toParams) {
_runningAnimations--;
if (_runningAnimations === 0) {
$state.go(toState.name, toParams);
}
}
}
})();
So it's possible to use it in the HTML for the element which I want to animate
<div class="main" cg-animate-element>
...
</div>
And the final CSS:
.main {
&.ng-animate {
transition: opacity, transform;
transition-duration: 0.4s;
transition-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
}
&.ng-enter {
opacity: 0;
transform: translate3d(0, 100px, 0);
}
&.ng-enter-active {
opacity: 1;
transform: translate3d(0, 0, 0);
}
&.ng-leave {
opacity: 1;
transform: translate3d(0, 0, 0);
}
&.ng-leave-active {
opacity: 0;
transform: translate3d(0, 100px, 0);
}
}
Related
I need to implement toggle functionality for the widget. When the user clicks on the minimization button then widget should shrink and expand when click on maximize button respectively.
I'm trying to achieve this functionality with below piece of code.
Functionality working as expected but it is registering the event multiple times(I'm emitting the event and catching in the filterTemplate directive).
How can we stop registering the event multiple times ?
Or
Is there anyway to like compiling once and on toggle button bind the template/directive to DOM and to make it work rest of the functionality .
So could you please help me to fix this.
function bindFilterTemplate(minimize) {
if ($scope.item && !minimize) {
if ($scope.item.filterTemplate) { // filter template is custom
// directive like this
// "<widget></widget>"
$timeout(function () {
var filterElement = angular.element($scope.item.filterTemplate);
var filterBody = element.find('.cls-filter-body');
filterElement.appendTo(filterBody);
$compile(filterElement)($scope); // Compiling with
// current scope on every time when user click on
// the minimization button.
});
}
} else {
$timeout(function () {
element.find('.cls-filter-body').empty();
});
}
}
bindFilterTemplate();
// Directive
app.directive('widget', function () {
return {
restrict: 'E',
controller: 'widgetController',
link: function ($scope, elem) {
// Some code
}
};
});
// Controller
app.controller('widgetController', function ($scope) {
// This event emitting from parent directive
// On every compile, the event is registering with scope.
// So it is triggering multiple times.
$scope.$on('evt.filer', function ($evt) {
// Server call
});
});
I fixed this issue by creating new scope with $scope.$new().
When user minimizes the widget destroying the scope.
Please let me know if you have any other solution to fix this.
function bindFilterTemplate(minimize) {
// Creating the new scope.
$scope.newChildScope = $scope.$new();
if ($scope.item && !minimize) {
if ($scope.item.filterTemplate) {
$timeout(function () {
var filterElement = angular.element($scope.item.filterTemplate);
var filterBody = element.find('.cls-filter-body');
filterElement.appendTo(filterBody);
$compile(filterElement)($scope.newChildScope);
});
}
} else {
$timeout(function () {
if ($scope.newChildScope) {
// Destroying the new scope
$scope.newChildScope.$destroy();
}
element.find('.cls-filter-body').empty();
});
}
}
I'm using the Angular UI bootstrap modal and I ran into a bit of a problem.
I want to call a function when the bootstrap modal dismiss animation is finished. The code block below will call the cancel() function as soon as the modal starts to be dismissed - and NOT when the modal dismiss animation has finished.
Angular UI does not use events, so there is no 'hidden.bs.modal' event being fired (at least, not to my knowledge).
var instance = $modal.open({...});
instance.result.then(function(data) {
return success(data);
}, function() {
return cancel();
})
The cancel() block immediately runs when the modal starts to close. I need code to execute when the closing animation for the Bootstrap modal finishes.
How can I achieve this with angular UI?
Component for reference:
https://angular-ui.github.io/bootstrap/#/modal
Thanks!
A little late but hope it still helps! You can hijack the uib-modal-window directive and check when its scope gets destroyed (it is an isolated scope directive). The scope is destroyed when the modal is finally removed from the document. I would also use a service to encapsulate the functionality:
Service
app.service('Modals', function ($uibModal, $q) {
var service = this,
// Unique class prefix
WINDOW_CLASS_PREFIX = 'modal-window-interceptor-',
// Map to save created modal instances (key is unique class)
openedWindows = {};
this.open = function (options) {
// create unique class
var windowClass = _.uniqueId(WINDOW_CLASS_PREFIX);
// check if we already have a defined class
if (options.windowClass) {
options.windowClass += ' ' + windowClass;
} else {
options.windowClass = windowClass;
}
// create new modal instance
var instance = $uibModal.open(options);
// attach a new promise which will be resolved when the modal is removed
var removedDeferred = $q.defer();
instance.removed = removedDeferred.promise;
// remember instance in internal map
openedWindows[windowClass] = {
instance: instance,
removedDeferred: removedDeferred
};
return instance;
};
this.afterRemove = function (modalElement) {
// get the unique window class assigned to the modal
var windowClass = _.find(_.keys(openedWindows), function (windowClass) {
return modalElement.hasClass(windowClass);
});
// check if we have found a valid class
if (!windowClass || !openedWindows[windowClass]) {
return;
}
// get the deferred object, resolve and clean up
var removedDeferred = openedWindows[windowClass].removedDeferred;
removedDeferred.resolve();
delete openedWindows[windowClass];
};
return this;
});
Directive
app.directive('uibModalWindow', function (Modals) {
return {
link: function (scope, element) {
scope.$on('$destroy', function () {
Modals.afterRemove(element);
});
}
}
});
And use it in your controller as follows:
app.controller('MainCtrl', function ($scope, Modals) {
$scope.openModal = function () {
var instance = Modals.open({
template: '<div class="modal-body">Close Me</div>' +
'<div class="modal-footer"><a class="btn btn-default" ng-click="$close()">Close</a></div>'
});
instance.result.finally(function () {
alert('result');
});
instance.removed.then(function () {
alert('closed');
});
};
});
I also wrote a blog post about it here.
I'm trying to build a simple infinite scroll. It loads the data fine but after loading, new added elements' directives don't work.
This is relevant part of the scroll checking and data loading directive.
.directive("scrollCheck", function ($window, $http) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
// calculating windowBottom and docHeight here then
if (windowBottom >= (docHeight - 100)) {
// doing some work here then
$http.get('service page').then(function (result) {
if (result.data.trim() != "") {
var newDiv = angular.element(result.data);
element.append(newDiv);
}
// doing some other work
},function () {
// error handling here
});
}
scope.$apply();
});
};
})
Service page returns some repeats of this structure as result.data
<div ...>
<div ... ng-click="test($event)"></div>
<div ...>...</div>
</div>
As i said data loads just fine but those test() functions in ng-clickdirectives don't work. How to get em work?
I believe you are going to need to compile the html element returned. Something like this
$compile(newDiv)(scope); // Corrected. Thanks
You'll need to be sure and pass in $compile into your function
Can anyone suggest me how to disable animations in angular js application while executing protractor tests. I have added below code in my protractor config file but that does not help me:
var disableNgAnimate = function() {
angular.module('disableNgAnimate', []).run(function($animate) {
$animate.enabled(false);
});
};
browser.addMockModule('disableNgAnimate', disableNgAnimate);
You can check out the angular's protractor configuration:
https://github.com/angular/angular.js/blob/master/protractor-shared-conf.js
You should add it under onPrepare block:
onPrepare: function() {
/* global angular: false, browser: false, jasmine: false */
// Disable animations so e2e tests run more quickly
var disableNgAnimate = function() {
angular.module('disableNgAnimate', []).run(['$animate', function($animate) {
$animate.enabled(false);
}]);
};
browser.addMockModule('disableNgAnimate', disableNgAnimate);
I personally use the following code in the "onPrepare" function in my 'conf.js' file to disable both Angular/CSS animations:
...
onPrepare: function() {
var disableNgAnimate = function() {
angular
.module('disableNgAnimate', [])
.run(['$animate', function($animate) {
$animate.enabled(false);
}]);
};
var disableCssAnimate = function() {
angular
.module('disableCssAnimate', [])
.run(function() {
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '* {' +
'-webkit-transition: none !important;' +
'-moz-transition: none !important' +
'-o-transition: none !important' +
'-ms-transition: none !important' +
'transition: none !important' +
'}';
document.getElementsByTagName('head')[0].appendChild(style);
});
};
browser.addMockModule('disableNgAnimate', disableNgAnimate);
browser.addMockModule('disableCssAnimate', disableCssAnimate);
}
...
Please note: I did not write the above code, I found it online while looking for ways to speed up my own tests.
Disabling CSS Animations / Transitions
In addition to disabling ngAnimation (ie, element(by.css('body')).allowAnimations(false);), you may need to disable some animation that has been applied through CSS.
I have found this sometimes contributes to some such animated elements, that may appear to Protractor to be 'clickable' (ie, EC.elementToBeClickable(btnUiBootstrapModalClose)), to not actually respond to .click(), etc.
In my particular case, I was suffering with a ui.bootstrap modal that transitioned in and out, and I wasn't always able to get its internal 'close' button reliably clicked.
I found that disabling css animations helped. I added a class to a stylesheet:
.notransition * {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
... and in protractor, I've got something like:
_self.disableCssAnimations = function() {
return browser.executeScript("document.body.className += ' notransition';");
};
There may be slicker ways of applying this concept, but I found that the above worked very well for me - in addition to stabilising the tests, they run quicker as they're not waiting for animations.
See this for an example: https://github.com/angular/protractor/blob/master/spec/basic/elements_spec.js#L123
it('should export an allowAnimations helper', function() {
browser.get('index.html#/animation');
var animationTop = element(by.id('animationTop'));
var toggledNode = element(by.id('toggledNode')); // animated toggle
// disable animation
animationTop.allowAnimations(false);
// it should toggle without animation now
element(by.id('checkbox')).click();
});
I'm sure this is going to be a "dont do that!" but I am trying to display the style on an angular element.
<div ng-repeat="x in ['blue', 'green']" class="{{x}}">
<h3 insert-style>{{theStyle['background-color']}}</h3>
</div>
Result would be
<div class='blue'><h3>blue(psudeo code hex code)</h3></div>
<div class='green'><h3>green(psudeo code hex code)</h3></div>
I basically need to get the style attributes and display them.
Directive Code...
directives.insertStyle = [ function(){
return {
link: function(scope, element, attrs) {
scope.theStyle = window.getComputedStyle(element[0], null);
}
}
}];
Fiddle example: http://jsfiddle.net/ncapito/G33PE/
My final solution (using a single prop didn't work, but when I use the whole obj it works fine)...
Markup
<div insert-style class="box blue">
<h4 > {{ theStyle['color'] | toHex}} </h4>
</div>
Directive
directives.insertStyle = [ "$window", function($window){
return {
link: function(scope, element, attrs) {
var elementStyleMap = $window.getComputedStyle(element[0], null);
scope.theStyle = elementStyleMap
}
}
}];
Eureka!
http://jsfiddle.net/G33PE/5/
var leanwxApp = angular.module('LeanwxApp', [], function () {});
var controllers = {};
var directives = {};
directives.insertStyle = [ function(){
return {
link: function(scope, element, attrs) {
scope.theStyle = window.getComputedStyle(element[0].parentElement, null)
}
}
}];
leanwxApp.controller(controllers);
leanwxApp.directive(directives);
So that just took lots of persistence and guessing. Perhaps the timeout is unnecessary but while debugging it seemed I only got the style value from the parent after the timeout occurred.
Also I'm not sure why but I had to go up to the parentElement to get the style (even though it would realistically be inherited (shrug)?)
Updated fiddle again
Did one without the timeout but just looking at the parentElement for the style and it seems to still work, so scratch the suspicions about the style not being available at all, it's just not available where I would expect it.
Also holy cow there are a lot of ways to debug in Chrome:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
I used
debugger;
statements in the code to drop in breakpoints without having to search all the fiddle files.
One more quick update
The code below comes out of Boostrap-UI from the AngularUI team and claims to provide a means to watch the appropriate events (haven't tried this but it looks like it should help).
http://angular-ui.github.io/bootstrap/
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* #param {DOMElement} element The DOMElement that will be animated.
* #param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* #return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {
var $transition = function(element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"];
var transitionEndHandler = function(event) {
$rootScope.$apply(function() {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function() {
if ( angular.isString(trigger) ) {
element.addClass(trigger);
} else if ( angular.isFunction(trigger) ) {
trigger(element);
} else if ( angular.isObject(trigger) ) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if ( !endEventName ) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function() {
if ( endEventName ) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames){
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
The issue you'll face is that getComputedStyle is considered a very slow running method, so you will run into performance issues if using that, especially if you want angularjs to update the view whenever getComputedStyle changes.
Also, getComputedStyle will resolve every single style declaration possible, which i think will not be very useful. So i think a method to reduce the number of possible style is needed.
Definitely consider this an anti-pattern, but if you still insist in this foolishness:
module.directive('getStyleProperty', function($window){
return {
//Child scope so properties are not leaked to parent
scope : true,
link : function(scope, element, attr){
//A map of styles you are interested in
var styleProperties = ['text', 'border'];
scope.$watch(function(){
//A watch function to get the styles
//Since this runs every single time there is an angularjs loop, this would not be a very performant way to do this
var obj = {};
var computedStyle = $window.getComputedStyle(element[0]);
angular.forEach(styleProperties, function(value){
obj[value] = computedStyle.getPropertyValue(value);
});
return obj;
}, function(newValue){
scope.theStyle = newValue;
});
}
}
});
This solution works if you don't HAVE to have the directive on the child element. If you just place the declaration on the ng-repeat element itself, your solution works:
<div insert-style ng-repeat="x in ['blue', 'green']" class="{{x}}">
Fiddle