AngularJS - How do I get access to my template in a directive? - angularjs

Given the following directive:
myApp.directive("test", function () {
return {
restrict: 'E',
scope: {
model: "="
},
template: "<div id='dialog_{{model.dialogId}}'></div>",
replace: true,
link: function (scope, element, attrs) {
alert($("dialog_" + scope.model.dialogId).length); <-- This is 0
}
}
});
I need to run a jQuery UI method on the div in the template, but I can't seem to get a reference to it from the DOM in my link function. Is there a way to run a function after the template has been added to the DOM?

You have element property.
You can do something like var div= element.find("div");
And if you want attach jquery plugin, just do $(div).jqueryPlugin();, you have to include jQuery, but if you don't angular provides jQuery Lite.

What I ended up doing was this:
link: function (scope, element, attrs) {
$timeout(function () {
alert($("#dialog_" + scope.model.dialogId).length);
}, 0);
}
I forgot to put the # in front of the selector, but it still only works if I use the timeout. Not sure why.

Related

Directive within another directive - scope var undefined

I'm trying to generate a smart-table directive from within a custom directive I've defined:
<div ng-controller="myContrtoller">
<containing-directive></containing-directive>
</div>
The directive definition:
angular.module('app')
.directive('containingDirective', function() {
return {
restrict: 'E',
replace: true,
template: '<table st-table="collection" st-pipe="scopeFun"></table>',
link: function(scope, elem, attrs) {
scope.scopeFun = function () {
// solve the misteries of life
}
}
}
});
As you can see my directive tries to replace the element by the template generated by the st-table directive, using the st-pipe directive depending on the first, briefly:
ng.module('smart-table')
.controller('stTableController' function () {
// body...
})
.directive('stTable', function () {
return {
restrict: 'A',
controller: 'stTableController',
link: function (scope, element, attr, ctrl) {
// body
}
};
})
.directive('stPipe', function (config, $timeout) {
return {
require: 'stTable',
scope: {
stPipe: '='
},
link: {
pre: function (scope, element, attrs, ctrl) {
var pipePromise = null;
if (ng.isFunction(scope.stPipe)) { // THIS IS ALWAYS UNDEFINED
// DO THINGS
}
},
post: function (scope, element, attrs, ctrl) {
ctrl.pipe();
}
}
};
});
Problem:
The st-pipe directive checks the scope var stPipe if it is defined or not by: if (ng.isFunction(scope.stPipe)). This turns out to be ALWAYS undefined. By inspecting I found two things:
From the stPipe directive, the value supposed to be scope.stPipe that is my scopeFun defined within my containingDirective is undefined on the scope object BUT defined within the scope.$parent object.
If I define my $scope.scopeFun within the myContrtoller I don't have any problem, everything works.
Solution:
I did find a solutions but I don't know what really is going on:
Set replace: false in the containingDirective
Define the scope.scopeFun in the pre-link function of containingDirective
Questions:
Why is the scopeFun available in the stPipe directive scope object if defined in the controller and why it is available in the scope.$parent if defined in the containingDirective?
What is really going on with my solution, and is it possible to find a cleaner solution?
From the docs: "The replacement process migrates all of the attributes / classes from the old element to the new one" so what was happening was this:
<containing-directive whatever-attribute=whatever></containing-directive>
was being replaced with
<table st-table="collection" st-pipe="scopeFun" whatever-attribute=whatever></table>
and somehow st-table did not enjoy the extra attributes (even with no attributes at all..).
By wrapping the containingDirective directive template within another div fixed the problem (I can now use replace:true):
<div><table st-table="collection" st-pipe="scopeFun"></table></div>
If someone has a more structured answer would be really appreciated

dynamically add ui-sref to an element

I have the following directive
.directive('famAction', function () {
var directive = {
restrict: 'A',
scope: {action: '='},
link: link
};
function link(scope, element) {
if (scope.action.hasOwnProperty('state')) {
element.attr('ui-sref', scope.action.state);
}
if (scope.action.hasOwnProperty('func')) {
element.bind('click', scope.action.func);
}
}
return directive;
})
The problem is that, when adding the ui-sref attribute, the attribute isn't compiled ant therefore I don't have the generater href tag, so the link doesn't work.
How can I do to dynamically add a ui-sref attribute to an element and then compile it ?
I even tried this, without success:
.directive('famAction', function () {
var directive = {
restrict: 'A',
scope: {action: '='},
compile: compile
};
function compile(tElement, tAttrs) {
return {
pre: function preLink(scope, element, attrs) {
if (scope.action.hasOwnProperty('state')) {
element.attr('ui-sref', scope.action.state);
}
},
post: function postLink(scope, element, attrs) {
if (scope.action.hasOwnProperty('func')) {
element.bind('click', scope.action.func);
}
}
};
}
return directive;
})
PS: My action object can be one of the following:
{state: 'app.flaws.relevant', icon: 'chain-broken'}
{func: vm.ignoreFlaw, icon: 'ambulance'}
You cannot add directives to the element currently being compiled! The reason is that Angular has already parsed it and extracted the directives to be compiled. In contrast, if you wanted to add an attribute directive to an internal element, you should do it in the compile function (not in preLink - the template has already been compiled there and the addition of the attribute would have no effect). For cases like this, where you want access to the scope, it will not work: compile cannot access the scope (it has not been created yet).
What can you do in your case?
Manual compilation:
Remove the element that has the ui-sref from the template of your famAction directive.
In pre- or postLink, use $compile to compile the template of the element that contains the ui-sref, i.e. something along the lines of:
var uiSrefElem = $compile(
'<button ui.sref="' + scope.action.state + '">Go!</button>'
);
Add this uiSrefElem to the element of the directive.
Programmatic navigation: Place a function in the scope/controller that uses $state.go(scope.action.state). Call this function when the directive element is clicked.
I would go for (2).

AngularJS: Getting text from TD in directive attached via an attribute and raising event in controller $scope?

I seem to have a small issue. I have created a directive and inserted the directive via an attribute on an existing DIV, see below.
<td my-directive>This Text I want to get hold of in my directive</td>
and the directive is displayed here. I did try playing around with element.parent() but this doesn't seem to work.
.directive('myDirective', function () {
return {
template: '<div></div>',
restrict: 'A',
link: function(scope, element, attrs) {
element.text(element.parent().text); // Doesn't work
}
};
});
I want the TD to continue with its normal operation i.e. Displaying the text with the TD element. But its blank, so I thought about re-injecting it in the directive, but why is it blank?
Actually what I am trying to do is any part of the directive is clicked I want to do some internal stuff and then raise an event on the $scope which is shared by controller i.e.
element.click(function(){
//alert("direc clicked");
scope.onClick()
});
Not sure if I am doing this correct.
Anyone done this before ?
I think you just need to add ng-transclude in your template:
.directive('myDirective', function () {
return {
template: '<div ng-transclude></div>',
transclude: true,
restrict: 'A',
link: function(scope, element, attrs) {
element.text(element.parent().text); // Doesn't work
}
};
});
source

angular - Listening on transcluded change

I have a simple directive
angular.module('myApp')
.directive('myDirective', function () {
return {
template: '<p ng-transclude></p>',
restrict: 'A',
transclude: true,
link: function postLink(scope, element, attrs) {
}
}
}
);
I am trying to run code each time the transclusion content changes and the directive is rendered - I need the transcluded content.
Example algorithm I would like to run in this case is:
count words of transcluded content.
I have tried scope.$watch in multiple forms but to no avail.
We can use the jqlite included within Angular inside a watch expression function to accomplish this. Below is code that watches the length of the transcluded element using jqLite (element.text().length). The watch fires whenever the length of the element that this directive is attached to changes.
And the new length is passed in as newValue to the second function within the watch (since we return it from the first watch function).
myApp.directive('myDirective', function () {
return {
template: '<p ng-transclude></p>',
restrict: 'A',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
scope.$watch(function () {
return element.text().length;
},
function (newValue, oldValue) {
console.log('New Length ', newValue);
});
}
}
});
I've got a working jsfiddle here:
http://jsfiddle.net/2erbF/6/
This addresses the word/letter count scenario. But you could write a test on the element.text() itself if you needed it to fire on any changes- not just a length change.

How to hide element if transcluded contents are empty?

I created a very simple directive which displays a key/value pair. I would like to be able to automatically hide the element if the transcluded content is empty (either zero length or just whitespace).
I cannot figure out how to access the content that gets transcluded from within a directive.
app.directive('pair', function($compile) {
return {
replace: true,
restrict: 'E',
scope: {
label: '#'
},
transclude: true,
template: "<div><span>{{label}}</span><span ng-transclude></span></div>"
}
});
For example, I would like the following element to be displayed.
<pair label="My Label">Hi there</pair>
But the next two elements should be hidden because they don't contain any text content.
<pair label="My Label"></pair>
<pair label="My Label"><i></i></pair>
I am new to Angular so there may be a great way handle this sort of thing out of the box. Any help is appreciated.
Here's an approach using ng-show on the template and within compile transcludeFn checking if transcluded html has text length.
If no text length ng-show is set to hide
app.directive('pair', function($timeout) {
return {
replace: true,
restrict: 'E',
scope: {
label: '#'
},
transclude: true,
template: "<div ng-show='1'><span>{{label}} </span><span ng-transclude></span></div>",
compile: function(elem, attrs, transcludeFn) {
transcludeFn(elem, function(clone) {
/* clone is element containing html that will be transcludded*/
var show=clone.text().length?'1':'0'
attrs.ngShow=show;
});
}
}
});
Plunker demo
Maybe a bit late but you can also consider using the CSS Pseudo class :empty.
So, this will work (IE9+)
.trancluded-item:empty {
display: none;
}
The element will still be registered in the dom but will be empty and invisible.
The previously provided answers were helpful but didn't solve my situation perfectly, so I came up with a different solution by creating a separate directive.
Create an attribute-based directive (i.e. restrict: 'A') that simply checks to see if there is any text on all the element's child nodes.
function hideEmpty() {
return {
restrict: 'A',
link: function (scope, element, attr) {
let hasText = false;
// Only checks 1 level deep; can be optimized
element.children().forEach((child) => {
hasText = hasText || !!child.text().trim().length;
});
if (!hasText) {
element.attr('style', 'display: none;');
}
}
};
}
angular
.module('directives.hideEmpty', [])
.directive('hideEmpty', hideEmpty);
If you only want to check the main element:
link: function (scope, element, attr) {
if (!element.text().trim().length) {
element.attr('style', 'display: none;');
}
}
To solve my problem, all I needed was to check if there were any child nodes:
link: function (scope, element, attr) {
if (!element.children().length) {
element.attr('style', 'display: none;');
}
}
YMMV
If you don't want to use ng-show every time, you can create a directive to do it automatically:
.directive('hideEmpty', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: {
post: function (scope, elem, attrs) {
$timeout(function() {
if (!elem.html().trim().length) {
elem.hide();
}
});
}
}
};
}]);
Then you can apply it on any element. In your case it would be:
<span hide-empty>{{label}}</span>
I am not terribly familiar with transclude so not sure if it helps or not.
but one way to check for empty contents inside the directive code is to use iElement.text() or iElement.context object and then hide it.
I did it like this, using controllerAs.
/* inside directive */
controllerAs: "my",
controller: function ($scope, $element, $attrs, $transclude) {
//whatever controller does
},
compile: function(elem, attrs, transcludeFn) {
var self = this;
transcludeFn(elem, function(clone) {
/* clone is element containing html that will be transcluded*/
var showTransclude = clone.text().trim().length ? true : false;
/* I set a property on my controller's prototype indicating whether or not to show the div that is ng-transclude in my template */
self.controller.prototype.showTransclude = showTransclude;
});
}
/* inside template */
<div ng-if="my.showTransclude" ng-transclude class="tilegroup-header-trans"></div>

Resources