AngularJS directive: Updating the isolated scope - angularjs

I want to create a directive which displays changing data. For simplicity let's say I want to display the current time. This means that once a second the directive needs to refresh itself.
In the docs there is an example for just this case (plunkr), but it procedurally updates the directive's content. I wonder if it could be done using data binding as well.
I imagine something like this:
module.directive('dateTime', function($interval) {
return {
scope: { // start with an empty isolated scope
},
template: '{{currentTime}}', // display time fetched from isolated scope
init: function(isolatedScope) {
$interval(function() {
isolatedScope.currentTime = new Date(); /* update isolated scope */
}, 1000);
},
destroy: function() { /* stop interval */ }
};
}
Is something like that possible? How?

Sure it's possible. The init() function you use in your code must be named link, and the destroy() function must be replaced by a listener on the $destroy event on the element passed to the link function:
module.directive('dateTime', function($interval) {
return {
scope: {
},
template: '{{currentTime}}',
link: function(isolatedScope, element) {
var interval = $interval(function() {
isolatedScope.currentTime = new Date(); /* update isolated scope */
}, 1000);
element.on('$destroy', function() {
$interval.cancel(interval);
});
}
};
}
Working example: http://plnkr.co/edit/rjwYZmR4qJ9Jn28d3jXR?p=preview

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

Widget toggle functionality with $compile

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

ngMessages with custom validator in parent controller

I'm trying to figure out how to wire up a custom validator with ngMessages that has access to the parent scope. I have an input field for an address and onBlur I want to do a geolocate of the address and update the position of a marker on a map (by setting two variables on the controllers this).
Custom validator examples use directives (and I have followed those for a basic example) but can't move from their to geolocation, as I'm struggling with Directive to parent Controller communication in the context of ES6, ControllerAs,...:
I've started off trying to access the parent controller from the link function with scope.$parent (How to access parent scope from within a custom directive *with own scope* in AngularJS?) but I'm using ES6 classes and it just did not seem to work.
now I'm thinking about passing in the parent function to the Directive, but the function is complaining that it cannot find elements of the controller's normal scope, so that means it cannot update the marker's position.
Grateful for advice on wiring this up.
Here's where I got to in the second instance
var checkAddressDir = function($timeout) {
return {
require : 'ngModel',
scope: {
geolookup: '&'
},
link : function(scope, element, attrs, ngModel) {
function setAsLoading(bool) {
ngModel.$setValidity('recordLoading', !bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
scope.geolookup()(value)
// scope.$parent.findAddress()
.then( res => {
// I'll use res to update ngModel.$setValidity
console.log(res);
setAsLoading(false);
});
// THE FOLLOWING SERVED TO GET ME STARTED
// $timeout(function() {
// console.log("timeout");
// setAsLoading(false);
// }, 1000);
return value;
})
}
}
}
And this is the controller function I need to be able to use with the controller's scope
findAddress(address) {
return this.$q( (resolve, reject) => {
mygeocoder.geocode(myOptions, (res, stat) => {
if (stat === google.maps.GeocoderStatus.OK) {
if (res.length > 1) {
console.log(`Need unique result, but got ${res.length}`);
return "notUnique";
}
var loc = res[0].geometry.location;
this.resto.lat = loc.lat();
this.resto.lng = loc.lng();
this.zoom = 16;
this.$scope.$apply();
return "good";
} else {
console.log(" not found - try again?");
return "notFound";
}
});
});

Angular Custom Directive - How to make it Behave Like Ng-if

I'm trying to build a custom directive to either show items on a page or completely remove them based on authorization data, and I'm clearly missing something, 'cuz its not working and I'm having a hard time figuring out why.
I've been following the guide here:
http://adamalbrecht.com/2014/09/22/authorization-with-angular-and-ui-router/
Which said to take a copy of the NgIf source code, and modify it (as I have below).
I'm really confused because not only is it not working as expected, but even when I put break-points within the function calls in the directive, it never hits those break points.
I'm not sure what I'm doing wrong. Is there something else not documented within the steps that I need to do in order to use a custom directive, or did I somehow miss a step? Regular ng-if's work on the same page just fine.
EDIT: I should note that AuthorizeService.isAuthorizedForOne returns a promise value which is either true or false. This works fine in other contexts.
'use strict';
/**
* #ngdoc directive
* #name ngIfPermission
* #restrict A
*
* #description
**/
var ngIfPermissionDirective = ['$animate', function($animate, AuthorizeService) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
console.log("I am here");
var block, childScope, previousElements;
$attr.$observe("ngIfPermission", function(value){
console.log("I am there");
var permissions = JSON.parse(value.replace(/'/g, '"'));
AuthorizeService.isAuthorizedForOne(permissions).then(function(auth){
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end ngIfPermission: ' + $attr.ngIfPermission + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
},
function(err) {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
});
});
}
};
}];
How I'm referencing it:
<div ng-if-permission="['OOGY']">You can see this.</div>
<div ng-if-permission='["BOOGY"]'>or this</div>
I think you might got the declaration for the directive wrong.
app.directive( 'ngIfPermissionDirective', function($animate){
//directive here
));
DEMO http://plnkr.co/edit/BhubrfMAiW3K4ANI3pTx

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