Using directives in AngularJS - javascript

I'm trying to learn AngularJS and have one question/concept I'm struggling to understand.
Take the following demo code I created:
js
var app = angular.module('customerPortalApp', ["ui.router"]);
app.config( function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1");
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "/static/html/partials/_campaign_title.html",
controller: "CampaignCtrl"
})
});
app.controller("CampaignCtrl", function($scope){
$scope.loadCampaign = function(){
alert("loaded campaign!")
}
});
app.directive("campaign", function() {
var MessageBox = angular.element('<div class="alert alert-success">hello</div>');
var link = function (scope, element){
scope.loadCampaign();
}
return {
restrict: "E",
compile: function (template){
template.append(MessageBox)
return link
}
}
});
html
<div class="container" ng-app="customerPortalApp">
<div class="row">
<div class="span12">
<div class="well" ui-view></div>
</div>
</div>
<div ng-controller="CampaignCtrl">
<campaign>
test
</campaign>
</div>
</div>
Looking at this code I call the controller in my config and the new $stateProvider I added now takes care of the template loading, so why do I now need directive? In my example I don't now know why I would need one, can ui-view be used to house more controllers?

For your example, you can to use a ui-view. In general, I used directives for a reusable and specified behavior.
What are Directives?
At a high level, directives are markers on a DOM element (such as an attribute, element name, or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.
Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngView. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.
See the documentation: Angular JS Documentation
A example below as I used the directives:
/* Get the boolean data and switch true or false for respective images. This Example use the bootstrap to show images */
App.directive('bool2image', function() {
return {
restrict: 'C',
replace: true,
transclude: true,
scope: { boolean: '#boolean' },
template: '<div ng-switch on="boolean">' +
'<div ng-switch-when="false"><span><i class=icon-remove></i></span></div>' +
'<div ng-switch-when="true"><span><i class=icon-ok></i></span></div>' +
'</div>'
}
});
So, to used the directive called into the code:
<div class="bool2image" boolean="{{booleanData}}"></div>
I hope to help you.

Related

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>

Pass data to transcluded element

I want to create a directive that organizes a displays data grouped by date. I also want to be able to specify a directive that will display the individual rows. In a perfect world it would look something like this (but nice and pretty)
Friday, Oct 28
[some directive html]
[some directive html]
[some directive html]
Saturday, Oct 29
[some directive html]
Sunday, Oct 30
[some directive html]
[some directive html]
...
This obviously doesn't work, so if you have a better approach please tell me, but I was hoping to be able to do something along these lines:
app.directive('dateOrganized', [function(){
return {
template:
'<div>' +
'<div ng-repeat="organizedDate in organizedDate">' +
'<div>{{organizedDate.date | date}}</div>' +
'<div ng-repeat="item in organizedDate.items">' +
'{{rowDirectiveHtml}}' +
'</div>' +
'</div>' +
'</div>',
scope: {
organizedDates: '=',
rowDirectiveHtml: '='
}
...
};
}])
app.directive('itemRow', [function(){
return {
template: '<div>{{item.data}}</div>',
scope: {
item: '='
}
};
}]);
then use it like this:
<div data-organized organized-dates="stuff" row-directive-html="<div item-row item=\"item\" />" />
I know this is super ugly (and doesn't work, but I'm sure I could get it working with a few tweaks) so what I am really asking, is there a better way to do this?
This question is more complicated than might appear, so let's break it down.
What you are building is a directive that accepts a partial template - <div item-row item="item" /> - and that template uses (or linked against a scope with) an inner variable - item - that is not defined in the outer scope by the user; its meaning is defined by your directive and your user "discovers" it by reading the documentation of your directive. I typically name such "magic" variables with a prefixed $, e.g. $item.
Step 1
Instead of passing a template as an HTML-as-string via attribute binding, pass it as contents and transclude that content. Transcluding allows you to bind the transcluded content against an arbitrary scope:
<foo>
<div>my item is: {{$item}}</div>
</foo>
.directive("foo", function(){
return {
scope: {},
transclude: true,
template: "<h1>I am foo</h1><placeholder></placeholder>",
link: function(scope, element, attrs, ctrls, transclude){
scope.$item = "magic variable";
transclude(scope, function(clonedContent){
element.find("placeholder").replaceWith(clonedContent);
});
}
};
});
The above will place the template <div>my item is: {{$item}}</div> (could be any template you specify) where the directive foo decides, and will link against a scope that has $item defined.
Step 2
But the added complexity of your directive is that it uses ng-repeat, which by itself accepts a template, and the template your directive receives needs to be used as a template of ng-repeat.
With just the approach above, this would not work, since by the time link runs, ng-repeat will have already transcluded its own content before you had a chance to apply yours.
One way to address that is to manually $compile the template of foo instead of using the template property. Prior to compiling, we will have a chance to place the intended template where needed:
.directive("foo", function($compile){
return {
scope: {},
transclude: true,
link: function(scope, element, attrs, ctrls, transclude){
scope.items = [1, 2, 3, 4];
var template = '<h1>I am foo</h1>\
<div ng-repeat="$item in items">\
<placeholder></placeholder>\
</div>';
var templateEl = angular.element(template);
transclude(scope, function(clonedContent){
templateEl.find("placeholder").replaceWith(clonedContent);
$compile(templateEl)(scope, function(clonedTemplate){
element.append(clonedTemplate);
});
});
}
};
});
Demo

AngularJS - calling methods on the parent scope from isolated scope directive not passing arguments

I'm just learning angular and creating some simple directives to try some things. I am having (what I think) is a small problem attempting to pass parameters from the directive to a controller function on the root scope.
Please see the following jsfiddle and note that I clicking the button (from within the directive) gives me undefined whereas it seems to work fine if clicking the button from the controller itself.
jsfiddle
Am I just missing something syntax wise? Or am I completely wrong in how this should work? I have made several attempts at placing variables in different locations (note the 'xxx') in the fiddle to see if anything would work and I get either errors or nothing.
<div ng-app="myApp" ng-controller="myController">
<!-- root scope -->
<div style="background-color: teal">
<button ng-click="propertyF('yyy')" >F</button>
</div>
<!-- directive firing methods on the root scope -->
<div style="background-color: coral">
<my-directive3 property6="propertyF()"></my-directive3>
</div>
</div>
var app = angular
.module('myApp', [])
.controller('myController', [
'$scope', function($scope) {
$scope.propertyF = function (aValue) {
alert("propertyF fired: '" + aValue + "'");
};
}
])
.directive('myDirective3', function() {
var directive = {
link : function link(scope, element, attrs) {
console.log("link directive 3");
},
restrict : 'EA',
replace : true,
scope : {
property6: '&'
},
template: '<button ng-click="property6(\'xxx\')">property6</button>'
};
return directive;
});
With the way Angular works, are you passing a function binding and specifying arguments. propertyF() does not specify any arguments.
property6="propertyF(arg)"
Then you can do Angular's unique syntax for handling this:
ng-click="property6({arg:\'xxx\'})"
http://jsfiddle.net/ue1trkt9/1/

Dynamic injection of directive inside another directive template

Hello I'm new to AngularJS and I think I misunderstood something. Im trying to inject dynamically a directive inside another directive template.
For instance I have 2 directives "a-tag" and "b-tag" and I would like to add one of these 2 directives inside another directive "container".
I have something like this:
<body ng-app="myApp">
<container item="a-tag" a-color="#f00"></container>
</body>
I declared my "container" directive to get the item attribute (a-tag, b-tag, or any other directive) and inject it.
angular.module("Container", []).directive("container", function($compile){
return {
restrict: "EA",
scope: {
item: "#"
},
link: function(scope, element, attrs){
var template = '<div id="container">';
var item = '';
if(scope.item !== undefined){
item = '<' + scope.item;
item += ' ></' + scope.item + '>';
}
template += item + '</div>';
element.html(template);
$compile(element.contents())(scope);
}
};
});
It is working but i dunt know how to broadcast to my child directive (a/b,etc.) his attributes (for instance a-color="#f00" like used in the first piece of code).
My child directives look like this:
angular.module("A", []).directive("aTag", function(){
return {
restrict: "EA",
templateUrl: "template/a.html",
replace: true,
link: function(scope, element, attrs){
element.css("color", attrs.bColor);
}
};
});
It is a simple example. Actually I designed a modal popup (my container) and I would like to use it for several things such as displaying a form, a loader (my directives a-tag, b-tag, etc).
Any idea is welcome.
Ty,
RĂ©mi

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.

Categories

Resources