Dynamically select directive based on data - javascript

I am trying to populate a table based on an array of objects. This array doesn't contain objects of the same type and for each row I'd like a completetly diferent style and, onclick function, basically a completely different behaviour.
For instance,
var data=[
{
type:'dir-b',
data: { ... }
},
{
type:'dir-b',
data: { ... }
},
{
type:'dir-c',
data: { ... }
}
]
For object type dirB I want a template and controller and for dirC a completely different function and template.
The solution I found was to create 3 directives. One of wich will run to determine one of the other two directives to add based on data.
.directive("dirA", function($compile){
return{
restrict:'A',
priority:1000,
terminal:true,
link: function(scope, element, attribute){
element.removeAttr("dir-a");//prevent endless loop
element.attr(attribute.type,"");
$compile(element)(scope);
}
}
})
.directive("dirB", function($compile){
return{
restrict:'A',
replace:true,
link: function(scope, element, attribute){
console.log("dirA");
}
}
})
.directive("dirC", function($compile){
return{
restrict:'A',
replace:true,
link: function(scope, element, attribute){
console.log("dirC");
}
}
});
Using <tr dir-a type='{{d.type}}' ng-repeat='d in data'/> is not having the desired effect. Either I give dirA a priority of 0 and it can parse the attribute but it's repeated more times than the array size, or I give it a priority of 1000 and it can't parse the b.type and use it as a literal.
Does anyone have a solution for this?

You could potentially use an ngSwitch here.
Plnkr
HTML
<div ng-repeat="(key, d) in data track by $index">
<div class="tbody" ng-switch on="d.type">
<div class="row" ng-switch-when="dir-b" dir-b>{{d}}</div>
<div class="row" ng-switch-when="dir-c" dir-c>{{d}}</div>
</div>
</div>
Then you just define dirB and dirC directives.
This doesn't display as an html table though, you can hopefully work from this though?

Not sure this was the best solution but it was the solution I found.
<table>
<tbody ng-repeat='d in data'>
<tr ng-if='d.type=="dir-b"' dir-b></tr>
<tr ng-if='d.type=="dir-c"' dir-c></tr>
</tbody>
</table>
This way due to ng-if only the correct row will ever be displayed but the problem is that tbody will be repeated as many row as there are in data. But until there is a beter solution this is how I did it.

Related

Ng-repeat using click to show/hide not working properly

This is the directive I'm using, there's a list of names that is dynamically generated from JSON. When you click on a name, it is suppose to show/hide a window with more info on that name. What happens instead is it shows/hides every window for every name in the list. I want it to just show/hide the window for the one I click on.
JS:
app.directive("taskListing", function() {
return {
restrict: 'E',
templateUrl: "/templates/elements/tasklisting.html",
scope: {},
link: function(scope, element, attrs, $sce){
element.on("click", function(){
angular.element("tbody.task-tbody tr").toggleClass("hidden");
});
},
};
});
HTML:
<table class="table" ng-controller="taskController">
<tbody class="task-tbody" ng-repeat="task in tasks" ng-if="task.title != ''">
<tr >
<td>
<span class='tasks-task'>{{task.title}}</span>
</td>
</tr>
<!--This table row is toggled show/hide-->
<tr class="hidden" bgcolor="#F8F8F8" >
<td>
<strong>Description:</strong>
<p>{{task.description}}</p>
</td>
</tr>
</tbody>
</table>
you have wrong query in angular.element("tbody.task-tbody tr") you must specify which tr you want to show
first hide all tr and then show only one with specific ID for example
angular.element("tbody.task-tbody tr").addClass('hidden');
angular.element("#task_8").removeClass('hidden');
specify task id in template:
<tr id="task_{{task.id}}">
It is difficult to be certain without your HTML, but I believe that your issue is angular.element("tbody.task-tbody tr").toggleClass("hidden");.
angular.element(document) aliases a jQuery function (ng docs). In this case it is aliasing a selector and selecting all of the rows in your "tbody.task-tbody tr". Thus, when you are calling .toggleClass("hidden"), jQuery is applying the "hidden" class to all of those elements.
Given that you only want to hide the element that has been clicked on, you can use the provided reference to the element in the directive to apply "hidden" exclusively to that element.
For example:
app.directive("taskListing", function() {
return {
restrict: 'E',
templateUrl: "/templates/elements/tasklisting.html",
scope: {},
link: function(scope, element, attrs, $sce){
element.on("click", function(){
// use element instead of 'angular.element'
element.toggleClass("hidden");
});
}
}
});
I think this will solve your problem.
The element you're listening the click event is the directive itself, so everytime you click on something inside the directive, every <tr> will have the toggleClass performed.
So instead of element.on("click",.... you should do element.find("tbody.task-tbody tr").on("click",....
And if you only want to toggle the visiblity of the <tr> with the #F8F8F8 background, I suggest you add a class to target it more easily.
[edit]
Your link function would be:
function(scope, element) {
element.find("tbody.task-tbody tr").on("click", function() {
this.toggleClass("hidden");
});
}

Add "A"-directive to parent node and execute

I'm a newbie in Angular.js and I stuck with one problem.
I want to integrate this plugin (https://github.com/pratyushmittal/angular-dragtable) to be able to drag columns in my table.
The whole table is a directive. Each <th> also renders by a directive.
<table>
<thead>
<tr>
<th ng-repeat="col in table.columns" my-column></th>
</tr>
</thead>
</table>
According to plugin documentation I need to set draggable directive to table. If I set it manually it doesn't grab my columns properly, because this columns is not rendered at that moment, and this doen't work. In my-column directive I'm waiting for last < th >
.directive('myColumn', ['$timeout', function($timeout) {
return {
restrict: 'A',
templateUrl: 'templates/column.html',
link: function(scope, element, attrs) {
if (scope.$last)
$timeout(function() {
//scope.$emit('lgColumnsRendered');
angular.element(element).closest('table').attr('draggable', 'draggable');
});
}
}
}])
And when last th is rendered I going up to my table and set this directive. For sure it is stupid and doesn't work. I also read about $compile but I need add attribute-directive to already existing table in my DOM.
Maybe I go wrong way and don't understand concept of doing this, but you catch the idea? How can I do this?
The problem is that angular-dragtable doesn't expect that table columns will be dynamic.
And I think it is logical assumption - in most cases table rows will be dynamic (which is OK for the dragtable), but columns are usually static.
The solution to this is to add a special event to the dragtable to ask it for re-initialization when your columns are created, here is the modification I made to dragtable (see the link to the full source below):
project.directive('draggable', function($window, $document) {
function make_draggable(scope, elem) {
scope.table = elem[0];
scope.order = [];
scope.dragRadius2 = 100;
var headers = [];
init();
// this is the event we can use to re-initialize dragtable
scope.$on('dragtable.reinit', function() {
init();
});
function init() {
headers = scope.table.tHead.rows[0].cells;
for (var i = 0; i < headers.length; i++) {
scope.order.push(i);
headers[i].onmousedown = dragStart;
}
}
function dragStart($event) {
Now in your code you can do this:
.directive('myColumn', ['$timeout', '$rootScope', function($timeout, $rootScope) {
return {
restrict: 'A',
templateUrl: 'templates/column.html',
link: function(scope, element, attrs) {
if (scope.$last)
$rootScope.$broadcast('dragtable.reinit');
}
}
Here is a full code of the example I tested the issue on.

How to loop over directives, compiling, and attaching to DOM?

I have a number of directives that I would like to compile and attach to the DOM. For example:
mod.controller("ctrl, ["$scope", "$compile", function($scope, $compile) {
$scope.tools = [
{
title: "foo",
directive: $compile("<foo-bar></foo-bar>")($scope)
},
{
title: "qux",
directive: $compile("<qux-bar></qux-bar>")($scope)
}
...
];
Then in HTML:
<div ng-repeat="tool in tools">
<div class="tool">
<h3>{{tool.title}}</h3>
{{tool.directive}}
</div>
</div>
I would like each directive to be compiled and injected into the DOM. But nothing happens. I expect because I am calling $compile too late. Is there a better way to do this?
FWIW, if I compile the directive and "manually" append it to the DOM, it works:
$('body').append($compile('<foo-bar></foo-bar>')($scope));
You cannot do it this way; the {{...}} bindings do not accept elements. They can be made to accept HTML, but this HTML is static - uncompiled.
If you want dynamic directives, you have to do it yourself. One option is with an auxiliary directive, e.g. the container-directive below:
<div class="tool" container-directive>
<h3>{{tool.title}}</h3>
<placeholder style="display: none"></placeholder>
</div>
It takes the tool from its context, $compiles it, and replaces the dummy placeholder element. Suppose the tools are defined as:
this.tools = [
{ title: 'foo', directive: 'foo-bar' },
{ title: 'qux', directive: 'qux-bar' }
];
Then a very simple implementation would be:
app.directive('containerDirective', function($compile) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.find('placeholder')
.replaceWith($compile('<' + scope.tool.directive + '></' + scope.tool.directive + '>')(scope));
}
};
});
See a fiddle: http://jsfiddle.net/kxj60cbo/
This code demonstrates the general idea. It definitely will need some adjustment to fit your needs. E.g. the directive is tightly coupled with the name of the iteration variable - tool - maybe using isolated scope would be better.
I wouldn't inject I would just qualify what to show
<div ng-repeat="tool in tools">
<div class="tool">
<h3>{{tool.title}}</h3>
<foo-bar ng-if="tool.title = 'foo'"></foo-bar>
<qux-bar ng-if="tool.title = 'qux'"></qux-bar>
</div>
</div>

Dynamically Create and Load Angular Directive

In my application i have a list of custom directive names.
$scope.data =["app-hello","app-goodby","app-goodafter"];
each name in this array is one directive that im created.
var app = angular.module('app',[]).controller('mainCtrl',function($scope){
$scope.data =["app-hello","app-goodby","app-goodafter"];
}).directive('appHello',function(){
return {
restrict:'EA',
template:'<h1>Hello Directive</h1>'
};
}).directive('appGoodbye',function(){
return {
restrict:'EA',
template:'<h1>GoodBye</h1>'
};
}).directive('appGoodafter',function(){
return{
restrict:'EA',
template:'<h1>Good Afternoon</h1>'
};
});
now i want to load directive with ng-repeat in the view for example because i used EA restrict for directive can create directive in ng-repeat like this :
<div ng-repeat="d in data" >
<div {{d}}></div>
</div>
but this way it doesn't work. so the real question is if i have list of directive how to load this directive with ng-repeat.for this scenario i create a jsbin .
thanks.
You need a "master" directive that $compiles the HTML (optionally containing directives) into an Angular-aware template and then links the compiled element to a $scope:
app.directive('master', function ($compile) {
return {
restrict: 'A',
link: function postLink(scope, elem, attrs) {
attrs.$observe('directive', function (dirName) {
if (dirName) {
var compiledAndLinkedElem =
$compile('<div ' + dirName + '></div>')(scope);
elem.html('').append(compiledAndLinkedElem);
}
});
}
};
});
<div master directive="{{dir}}" ng-repeat="dir in ['dir1', 'dir2', 'dir3']"></div>
See, also, this short demo.
You can do it in this way:
Directive:
app.directive('compile',function($compile){
return{
restrict:'A',
template: '<div></div>',
link:function(scope,elem,attrs){
scope.name = attrs.compile;
elem.children('div').attr(scope.name,'');
$compile(elem.contents())(scope);
}
};
});
HTML:
<div ng-repeat="d in data" compile="{{d}}">
</div>
Jsbin: http://jsbin.com/wofituye/4/edit
I actually prefer to create templates, that just contain the directive. Then you can use ng-include this then enables you to easily pass scope variables into the dynamically chosen directives too.
Here is my widget code fore example:
<div ng-repeat="widget in widgets track by $index" ng-include="widget.url" class="widget-container" ng-class="widget.widget_type.config.height +' ' + widget.widget_type.config.width">
</div>
Then I set the widget.url to a template containing just the right directive.
I can then in my directive do this:
<custom-widget ng-attr-widget="widget"></custom-widget>
Then I have access to the dynamic variable too, so I can access configuration specifics too, without having to dynamically generate HTML strings and compile them. Not a perfect solution, but personally I used to use the other approach mentioned, and discovered that this fit my needs much better.

Angular Directive Template Update on Data Load

I have a directive whose data is being received via an api call. The directive itself works fine, the problem arises (I believe) because the directive is loaded before the api call finishes. This results in the whole shebang just not working. Instead of my expected output, I just get {{user}}.
My directive looks like this:
app.directive('myDirective', function() {
return {
restrict: 'A',
require: '^ngModel',
scope: {
ngModel: '=',
},
template: '<tbody style="background-color: red;" ng-bind-html="renderHtml(listing_html)"></tbody>',
controller: ['$scope', '$http', '$sce',
function($scope, $http, $sce) {
$scope.listing_html += "<td>{{user.name}}</td>"
$scope.renderHtml = function(html_code) {
return $sce.trustAsHtml(html_code);
};
}
],
link: function(scope, iElement, iAttrs, ctrl) {
scope.$watch('ngModel', function(newVal) {
// This *is* firing after the data arrives, but even then the
// {{user}} object is populated. And the `user in ngModel` doesn't
// run correctly either.
console.log(scope.ngModel);
scope.listing_html = "<tr ng-repeat='user in ngModel'><td>{{user}}</td></tr>"
})
}
};
});
And my html is simply
<table my-directive my-options='{"Name": "name", "Email": "email"}' ng-model='userData'></table>
I've created a plunker with a ton of comments to hopefully help explain the issue.
This question is very similar to this one, with the key distinction of that solution not working. Adding ng-cloak to mine just makes it not display.
It may also be worth noting that I've been using this as reference on the way to construct a directive.
I think you're making this a bit more complicated that it needs to be. If you're going to try to insert dynamic HTML with Angular expressions in them, you need to use the $compile service to compile them first (this hooks up the directives, etc, in that dynamic HTML to Angular). With that said, I don't think you need to do that for what you're trying to accomplish.
Take a look at this updated plunk: http://plnkr.co/edit/RWcwIhlv3dMbjln4dOyb?p=preview
You can use the template in the directive to produce the dynamic changes you need. In my example, I've used ng-repeat to repeat over the users provided to the directive, and also to the options provided to the directive. ng-repeat does the watching, so as soon as the data provided to the directive via ng-model is updated, the ng-repeats reflect those changes.
<tbody style="background-color: red;">
<tr><th ng-repeat="option in myOptions">{{option.name}}</th></tr>
<tr ng-repeat="user in ngModel">
<td ng-repeat="option in myOptions">{{user[option.value]}}</td>
</tr>
</tbody>
The options I defined in the main controller like this.
$scope.tableOptions = [
{"name": "Name", "value": "name"},
{"name": "Email", "value": "email"}
];
You could add other properties to this that are used by the directive, such as display order, etc. You could even remove an item from the options dynamically and that data would then be removed from the output table.
Let me know if this helps, or if I've misunderstood what you were trying to accomplish.
I am not 100% sure, but I believe that ngBindHtml will not help you in this case.
ngBindHtml is for displaying some "normal" HTML, but you want to display some Angular, magic HTML.
For that you need to $compile the HTML to something that is Angular-aware and link the compiled HTML to a scope.
I used the following approach (with apparently good results):
controller: function ($scope, $element, $compile) {
var html = createTmpl(angular.fromJson($scope.myOptions));
$scope.$watch('ngModel', function (newVal) {
var elem = angular.element(html); // Creating element
var linkingFn = $compile(elem); // Compiling element
linkingFn($scope); // Linking element
$element.html(''); // Removing previous content
$element.append(elem); // Inserting new content
// The above is purposedly explicit to highlight what is
// going on. It's moe concise equivalent would be:
//$element.html('').append($compile(html)($scope));
});
where createTmpl() is defined to take into account myOptions and return the appropriate template for creating a table with a header-row (based on the keys of myOptions) and data-rows with the properties defined as myOptions's values:
function createTmpl(options) {
// Construct the header-row
var html = '<tr>';
angular.forEach(options, function (value, key) {
html += '<th>' + key + '</th>';
});
html += '</tr>\n';
// Construct the data-rows
html += '<tr ng-repeat="user in ngModel">';
angular.forEach(options, function (value, key) {
html += '<td>{{user' + value + '}}</td>';
});
html += '</tr>\n';
// Return the template
return html;
}
See, also, this short demo.
Of course, this is for demonstration purposes only and does not handle everything a production-ready app should (e.g. accounting for errors, missing properties, changes in myOptions and whatnot).
UPDATE:
I had very strong competion, so I did a slight modification of the code above in order to support nested properties. E.g. given an object with the following structure:
user = {
name: 'ExpertSystem',
company: {
name: 'ExpertSystem S.A.',
ranking: 100
}
};
we can have the company name displayed in a column of our table, just by defining myOptions like this:
myOptions='{"Company name": "company.name"}

Categories

Resources