Angular Directive not updating element using interval - angularjs

i have this directive
angular.module('mydirectives').directive('slideShow', function ($interval) {
return{
scope:{slideShow:'=slideShow'},
link:function(scope, element, attrs){
element.css("background-size","cover");
element.css("background-repeat","none");
element.css("background-position","center center");
element.css("background-blend-mode","color");
element.css("background-color","rgba(0, 0, 0, 0.5)");
scope.index=0;
function nextSlide()
{
if(!scope.slideShow) return;
if(scope.slideShow.sources.length===0) return;
var url=scope.slideShow.sources[scope.index++];
if(scope.index>=scope.slideShow.sources.length) scope.index=0;
element.css({'background-image': 'url(' + url +')'});
}
nextSlide();
var interval= $interval(nextSlide,3000)
scope.$on("$destroy",function(){
$interval.cancel(interval);
})
}
}
});
this is how i apply it
<section class="primary" slide-show="slideShow">
now the controller which provides property "slideShow" gets the value via http request. when it comes back with response it sets the value of slideShow like this
$scope.slideShow={sources:["http:\\sources\someimage.jgp"]}
webApi.getHomePageModel().then(function(model){
$scope.model=model;
$scope.slideShow=model.slideShow;
},function(error){
console.dir(error);
});
The Problem: when this runs only the default value of slideshow works and element's background-image is set but after the response to http the new value is set to slideShow but the when interval function "nextSlide" executes then background-image is not updated. in debugger i can see the url values is being picked up correctly but element is not updated.
EDIT:I was making a stupid mistake, the updated model was not as expected the elements in sources were not strings as expected (they were being generated as complex objects rather than string value.) all working now. also no need for scope.$applyAsync because the $interval service handles that for you

If you are using setInterval then you need to manually rerun angular's digetst cycle:
function nextSlide()
{
if(!scope.slideShow) return;
if(scope.slideShow.sources.length===0) return;
var url=scope.slideShow.sources[scope.index++];
if(scope.index>=scope.slideShow.sources.length) scope.index=0;
element.css({'background-image': 'url(' + url +')'});
scope.applyAsync(); //this line!
//May not work in older angular versions, if such you should use scope.apply()
}

I got it working with this implementation
angular.module('app').directive('slideShow', function ($interval) {
return{
scope:{slideShow:'=slideShow'},
link:function(scope, element, attrs){
var index=0;
function nextSlide()
{
if(!scope.slideShow) return;
if(scope.slideShow.images.length===0) return;
var url=scope.slideShow.images[index++];
if(index>=scope.slideShow.images.length) index=0;
element.css({'background-image': 'url(' + url +')'});
}
var interval=false;
var watchSlideShow=scope.$watch("slideShow",function(){
if(!scope.slideShow) return;
if(scope.slideShow.images.length===0) return;
if(interval) return;
nextSlide();
var interval= $interval(nextSlide,5000);
});
scope.$on("$destroy",function(){
$interval.cancel(interval);
watchSlideShow();
});
}
}
});

Related

Watcher not firing when contents of object changes

Why is my $interval visibly refreshing the model?
I'm trying to automatically update the song that I'm playing right now and showing it on my website. For that, I used the $interval function. The problem is that the model (div) is refreshing every 10 seconds, while I want it only to refresh when the song changes (and just checking every 10 seconds)
I tried changing the $interval function with setInterval(), but no luck.
angular.module('lastfm-nowplaying', [])
.directive('lastfmnowplaying', ['uiCreation', 'lastFmAPI', 'lastFmParser', '$interval', function(uiCreation, lastFmAPI, lastFmParser, $interval){
var link = function(scope, element, attrs){
scope.$watch('config', function(value) {
load();
});
var load = function(){
function SongCheck(){
var latestTrack;
if (scope.config){
if (scope.config.apiKey){
lastFmAPI.getLatestScrobbles(scope.config)
.then(function(data){
latestTrack = lastFmParser.getLatestTrack(data);
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}, function(reason) {
//Last.fm failure
});
}
else{
var latestTrack = {
title: scope.config.title,
artist: scope.config.artist,
largeImgUrl: scope.config.imgUrl,
xLargeImgUrl: scope.config.backgroundImgUrl,
}
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}
}
}
SongCheck();
$interval(function () {
SongCheck();
} , 8000);
}
};
return {
scope:{
config: '=config'
},
link: link
};
}])
The code works, but I want the model to change when a change is detected (in this case the json file).
Watcher not firing when contents of object changes
Delete the $interval timer and use the "deep watch" version of the watcher:
scope.$watch('config', function(value) {
load(value);
̶}̶)̶;̶
}, true);
Normally the watcher only fires when the object reference changes. Set the second argument to true to have the watcher fire when the object contents changes.
For more information, see
AngularJS Developer Guide - Scope $watch depths

How can you detect when HTML rendering is completed in AngularJS

I've done extensive research on this subject, but no matter what I do, I find it extremely difficult to achieve this objective.
I want to execute code when all elements have been fully rendered in AngularJS web application. I think I found solution suggesting to use routers and views, but I could not make that work on my case, as it seems it requires certain configuration.
When you have ng-repeat and a lot of nested directives that will generate HTML/Content based on various conditions using ng-if, I noticed that HTML rendering continues even after document ready event is fired or view content have been loaded ie $viewContentLoaded event is triggered.
The closest idea I have is to use $watch over the length of the children of the element of a given directive. Every time the $watch is executed, increment counter renderCount. Then, in another timer event, check if the counter renderCount didn't change over the past say 3-5 seconds, then we can make an assumption that rendering is done.
The code to watch for the children, and check if no more rendering is taking place, could be as follows:
app.directive('whenRenderingDone', function($interval, $parse){
return {
link: function (scope, el, attrs) {
var renderingCount = 0;
function watchForChildren() {
scope.$watch(function(){
return $(':input', el).length;
}, function(newVal, oldVal){
if (newVal) {
renderingCount++;
}
})
}
watchForChildren();
//Check counter every 3 seconds, if no change since last time, this means rendering is done.
var checkRenderingDone = $interval(function(){
var lastCount = lastCount || -1;
if (lastCount === renderingCount) {
var func = $parse(attrs.whenRenderingDone);
$interval.cancel(checkRenderingDone);
func(scope);
}
lastCount = renderingCount || -1;
}, 3000);
}
}
});
I will try to implement the above approach, and if you have feedback please let me know.
Tarek
I developed the following directive which is working well under Chrome and IE11:
app.directive('whenRenderingDone', function($timeout, $parse){
return {
link: function (scope, el, attrs) {
var lastCount;
var lastTimer = 5000; // Initial timeout
//Check counter every few seconds, if no change since last time, this means rendering is done.
var checkRenderingDone = function (){
var mainPromiseResolved = scope.mainPromiseResolved;
lastCount = lastCount || -1;
if (lastCount === el.find('*').length && mainPromiseResolved) {
console.log('Rendering done, lastCount = %i', lastCount);
var func = $parse(attrs.whenRenderingDone);
func(scope);
} else {
lastCount = el.find('*').length;
console.log('mainPromiseResolved = %s, lastCount %i', mainPromiseResolved, lastCount)
console.log('Rendering not yet done. Check again after %i seconds.', lastTimer/1000.00);
stopCheckRendering = $timeout(checkRenderingDone, lastTimer);
lastTimer = lastTimer - 1000;
if (lastTimer <= 0) {
lastTimer = 1000;
}
return stopCheckRendering;
}
}
var stopCheckRendering;
stopCheckRendering = checkRenderingDone();
el.on('$destroy', function() {
if (stopCheckRendering) {
$timeout.cancel(stopCheckRendering);
}
});
}
}
});
I hope this will be of help to you, and if you have any comment to improve, please let me know. See this to give you an idea about how it is working.
Tarek
You can use $$postDigest to run code after the digest cycle completes. You can read more about the scope lifecycle here
// Some $apply action here or simply entering the digest cycle
scope.$apply(function () { ... });
...
scope.$$postDigest(function () {
// Run any code in here that will run after all the watches complete
// in the digest cycle. Which means it runs once after all the
// watches manipulate the DOM and before the browser renders
});

Dynamically added element's directive doesn't work

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

Watch svg element after replaceWith in Angular Directive

Recently have been trying to build kind of a bulletproof directive for inserting inline svgs. It works pretty fine, but recently I wanted to add some animation triggered when class "animate" is add to the inserted element. Problem is that $watch applies to the old element (the one before replaceWith).
I have been trying anything, but I can not make it work. How to get an access to the element after the replacement?
Here is my code:
angular.module('test')
.directive('svgPng', ['$compile', function ($compile) {
return {
link: function(scope,elem,attrs) {
elem.on('load', function(){
var ext = function(s){return s.substr(s.length-3);},
src = attrs.src;
if (ext(src) === 'svg'){
if(window.Modernizr && window.Modernizr.svg){
Snap.load(src, function (svg){
elem = elem.replaceWith($compile(svg.node)(scope));
if(attrs.animate === 'true'){
scope.$watch(function() {return elem.attr('class'); }, function(newValue){
//some animation
}
}
console.log(elem); //gives old elem instead of svg.node
});
} else {
if(attrs.fallback){
elem.attr('src', attrs.fallback);
} else {
elem.attr('src', attrs.src.substr(3) + 'png');
}
}
}
});
}
};
}]);
elem isn't getting updated with the newly compiled element because .replaceWith doesn't return the new element. http://api.jquery.com/replacewith/
The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it
You need to store the compiled element and replace with that.
var compiled = $compile(svg.node)(scope);
elem.replaceWith(compiled);
elem = compiled;

Access Element Style from Angular directive

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

Resources