I have a little directive and I have troubles to make it working.
here is my directive :
angular
.module('thermofluor')
.directive('myCustomer', function() {
return {
restrict: 'E',
template: 'table_plate.html'
};
});
The template is just a paragraph with "Test" inside.
In my main HTML in call the directive with this :
<my-customer></my-customer>
but nothing appear on the screen, and in the html the directive is not replace with the directives output html
The template have the same name and is in the same folder.
What am I doing wrong ?
Thanks.
It should be templateUrl
return {
restrict: 'E',
templateUrl: 'table_plate.html'
};
If you only need the template to show, you can use ng-include instead directive:
<ng-include
src="string"
[onload="string"]
[autoscroll="string"]>
...
</ng-include>
There is also the version for any element available:
<ANY
ng-include="string"
[onload="string"]
[autoscroll="string"]>
...
</ANY>
For even more info glance on https://docs.angularjs.org/api/ng/directive/ngInclude
Under either src or ng-include put the reference to the template you wish to load (depending on what version you use). For only 1 restrict it's kinda overkill to use a directive, rest you get from this approach as well.
NOTE: in above definitions, attributes in brackets are not needed for your example.
Related
Scenario:-
I have html page rendering as angular template/view. Now there are big number of such template.
Now these templates has div in header part that is fixed through out the templates, now is there some-way that we can define one sub-template at one place and just insert that sub-template in all pages.
So that if there are any modification to be made, I will make in sub-template and that will be reflected in all the page.
Its like UserControls or Partials that we have in ASP.Net.
I am using AgularJS
Agreed that there are ui-routing for nested hosting but currently I am not looking for that.
Try
<div ng-include="path/to/template"></div>
you can create a seperate html file as template for header if it includes complex or considerable amount of elements. create a directive for this template and use it as an attribute/customTag or include it in your html using ng-include.
app.directive('header',function(){
return {
restrict: 'E', //'E': element /'A': attribute
templateUrl : 'templates/header.html'
}
});
use as attribute
<div header></div> // as Attribute
<header></header> // as element
if your header involves lot of functioning on it then you can also create a separate controller (which will act as a child controller) and add the controller to the above tags. such as
<header ng-controller="headerController"></header>
You probably want to use a directive template. This is a very simple directive with only the template information.
Eg:
<top-header></top-header>
module.directive('topHeader', function() {
return {
templateUrl: 'path',
// append
replace: true,
// attribute restriction
restrict: 'E'
}
});
In my MEAN app, I use jade as my template engine. My problem is, when I call an angular directive, jade code is not working but html code is working. My code is given below:
index.jade
div(ng-repeat="num in addDir")
admin-collection
directive.js
var formDir = angular.module("formDirective", []);
formDir.directive('adminCollection', function() {
return {
restrict: 'E',
transclude: true,
// call jade template url
templateUrl: '../_template/_formTemplate/_adminCollection.jade'
};
});
_adminCollection.jade
h1 from _adminCollection templateUrl
If I use jade format code in _adminCollection.jade, it just show a plain text, not text inside h1 tag
But following code is working:
directive.js
var formDir = angular.module("formDirective", []);
formDir.directive('adminCollection', function() {
return {
restrict: 'E',
transclude: true,
// call jade template url
templateUrl: '../_template/_formTemplate/_adminCollection.html'
};
});
_adminCollection.html code::
<h1> from _adminCollection templateUrl </h1>
How can I solve this problem?
Jade is a template engine. Browser has only built-in html parser, so it does not understand what jade code means and treats it as plaintext.
To make it work you need to convert it to html. You can use some task manager to do it. Two most popular task managers for node.js are gulp and grunt. Each of them has a working jade plugin which you can use right away.
Jade is something like less - it must be convert to another format, because browser can't understand that. When you use less, you have to transform it to css. And if you use jade - to html.
If you use grunt, you should look on it: https://github.com/gruntjs/grunt-contrib-jade
Otherwise you can check if your IDE can transform jade to html. For example PhpStorm can do this in automatic way.
Then in your directives you should specify path to html template, no jade.
You can use following directory structure:
app/
src/
js/
less/
jade/
dist/
templates/ <-- here you can put your htmls
styles/ <-- and here put css
js/ <-- if you want, you can put this minimalized app.js
that will contain all of your project,
see grunt-contrib-uglify for more info
EDIT: here is really great article about grunt: http://anthonydel.com/my-personal-gruntfile-for-front-end-experiments/ There is much more then you need, but maybe it will help you
.... Or you can to use webpack to do the work.
then you can load the template like this:
angular.module('app').component('myComponent', {
bindings: {},
template: require('./mytemplate.jade')()
});
You can to note that I'm invoking the returned function.
Another option is to keep the HTML templates in your DOM, but hidden:
div(ng-non-bindable, style="display: none")
#adminCollectionTemplate
div(ng-repeat="num in addDir")
admin-collection
#anotherTemplate
//- Alternatively, pull in the template from another file
include ./_formTemplate/_adminCollection.jade
and then use jQuery to fetch the HTML out of the DOM, and give it to angular:
formDir.directive('adminCollection', function() {
return {
restrict: 'E',
transclude: true,
// fetch template from DOM
template: $('#adminCollectionTemplate').html()
};
});
This will just work, without any Ajax or any task runners. But it will clutter up the DOM with templates that could otherwise be hidden away in the JS. And it is an extra step to place every new template into that div.
ng-non-bindable is needed to tell Angular to leave the template elements alone (don't manipulate them or bind to them), until their clones are actually used by the directive.
I am new to AngularJs. I am writing my custom angular directive which contains a template of some html content. When I use the template with the below code it works fine.
demoApp.directive('demoCarousel', function() {
return {
restrict: 'E',
replace:'true',
template: "<h1>This is from the custom directive..</h1>"
};
});
But when I replace the template with templateUrl pointing to a html inside a partial I am getting error.
demoApp.directive('demoCarousel', function() {
return {
restrict: 'E',
replace:'true',
templateUrl: "/partials/carousel.html"
};
});
The javascript error is something like:
Error: [$compile:tplrt] http://errors.angularjs.org/1.2.15/$compile/tplrt?p0=glassCarousel&p1=%2Fpartials%2Fcarousel.html
Please let me know where I am going wrong and what the correct way to use the templateUrl
Note: I am using only pure html code inside the carousel.html file.
The error sais: Template for directive 'glassCarousel' must have exactly one root element. /partials/carousel.html
this means that you have something like this in your template:
<div>...</div>
<div>...</div>
It is not allowed, you should have one root element:
<div>
<div>...</div>
<div>...</div>
</div>
I am new to AngularJs and struck with an issue. I have "index.html" where I need to have the main section loaded via the <div data-ng-view=""></div>. Now, the data inside the view will be populated by the controller using the below code
.when('/',
{
controller:'controllers.IndexCtrl',
templateUrl:'/partials/index-partial.html'
})
Inside the index-partial.html file I have used the custom directive linke below:
<custom-carousel/>
The code for the carousel is below:
myApp.directive('customCarousel', function() {
return {
restrict: 'E',
replace:'true',
templateUrl: "/partials/carousel.html",
link: function(scope, element, attrs) {
$('.my-list').click(function(){
$('.my-list').removeClass('active');
$(this).addClass('active');
});
}
};
});
The issue with the above approach is that the jquery code inside the directive gets called twice and hence the toggling of the selected li does not work.
I have below questions:
Is the jquery function inside the directive called twice because its called from the partial and once again during the ng-view?
Whats the reccommended way of handling this scenarios?
Whats the best approach to fix this issue. If I remove the templateUrl from the controller and directly use the custom-carousel inside the html, this works perfectly but I want to load the directive using the ng-view and not directly in the index.html file.
Please let me know the best approach to solve this issue.
I have a directive that has a dynamic template, now I want the directive to have the ability to use different controllers. Is it possible to dynamically assign a controller to a directive? If possible, would that be the same "ctrlr" then passed to the link function?
.directive('myDirective',['$compile',function($compile){
return {
restrict: 'AE',
replace: true,
transclude: true,
scope: {},
templateUrl: function(el,attrs){
return (angular.isDefined(attrs.template)) ? attrs.template : '/tmpls/default';
},
link : function(scope,el,attrs,ctrlr,transFn){
[... Do Stuff Here ...]
},
controller: [ DYNAMIC CONTROLLER ASSIGNMENT?? ]
};
}]);
While I didn't find the corresponding documentation for it in the official API, you can dynamically pass in the name of the controller you want to use by utilizing the "name" attribute in conjunction with providing the "controller" attribute with a value that uses the similar syntax you'd use for an isolate scope.
Using your sample code, assuming a controller called "myController":
HTML:
<my-directive ctrlr="myController"></my-directive>
JS:
.directive('myDirective',['$compile',function($compile){
return {
restrict: 'AE',
replace: true,
transclude: true,
scope: {},
templateUrl: function(el,attrs){
return (angular.isDefined(attrs.template)) ? attrs.template : '/tmpls/default';
},
link : function(scope,el,attrs,ctrlr,transFn){
[... Do Stuff Here ...]
},
controller: '#',
name: 'ctrlr'
};
}]);
This is how it is done:
Inside your directive element all you need is an attribute which gives you access to the name of the controller:
<card-dealer ng-repeat="card in cards" card="card"></card-dealer>
in my case my card attribute holds a card object which has a name property.
In the directive you set the isolate scope to:
scope: { card: '=' }
This isolates and interpolates the card object to the directive scope. You then set the directive template to:
template: '<div ng-include="getTemplateUrl()"></div>'
this looks to the directive's controller for a function named getTemplateUrl and allows you to set the templateUrl dynamically as well.
In the directive controller the getTemplateUrl function looks like this:
controller: ['$scope', '$attrs', function ($scope, $attrs) {
$scope.getTemplateUrl = function () {
return '/View/Card?cardName=' + $scope.card.name;
};
}]
I have an mvc controller which links up the proper .cshtml file and handles security when this route is hit, but this would work with a regular angular route as well.
In the .cshtml/html file you set up your dynamic controller by simply putting
<div ng-controller="CardContactController"></div>
as the root element. The controller will differ for each template. This creates a hierarchy of controllers which allows you to apply additional logic to all cards in general, and then specific logic to each individual card. I still have to figure out how I'm going to handle my services but this approach allows you to create a dynamic templateUrl and dynamic controller for a directive using an ng-repeat based on the controller name alone. It is a very clean way of accomplishing this functionality and it is all self-contained.