Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive template not rendering

I have a simple directive that just displays some text for now:

app.directive("exampleText", function() {
    return {
        restrict: "E",
        template: '<div>hello!</div>'
    }

});

In my index.html I have this:

<div class="container" ng-app="customerPortalApp">
  <div ui-view></div>
  <exampleText></exampleText>
</div>

exampleText is outside my ui-view as thats to do with my routes and works correctly. But its my understanding the directive template should render as is. Have I missed something?

like image 742
Prometheus Avatar asked Nov 23 '13 18:11

Prometheus


People also ask

What is attrs in AngularJS?

Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.

What is restrict in AngularJS directive?

Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name.

What is templateUrl in Angular?

When to use templateUrl in Angular applications? When you have a complex view, then it recommended by Angular to create that complex view in an external HTML file instead of an inline template. The Angular component decorator provides a property called templateUrl. This property takes the path of an external HTML file.


2 Answers

With a directive named:

app.directive("exampleText", ...

HTML should be:

<example-text></example-text>

From documentation:

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

like image 173
tasseKATT Avatar answered Oct 19 '22 18:10

tasseKATT


As tasseKATT noted the directive name should stay as "exampleText" and the html element should be <example-text>

I thought a demo may help demo

the template:

<div ng-app="myApp">
    <sample-text></sample-text>
</div>

the directive:

var app = angular.module('myApp', []);
app.directive('sampleText', function () {
    return {
        restrict: "E",
        template: '<div>Some sample text here.</div>'
    };
});
like image 2
klode Avatar answered Oct 19 '22 17:10

klode