AngularJS directive not displaying the template

前端 未结 3 1215
生来不讨喜
生来不讨喜 2020-12-16 21:01

Here is my AngularJs directive. Its\' expected to show the div in the template but it shown nothing while the code is run.

Here is the html

相关标签:
3条回答
  • 2020-12-16 21:35

    Angular normalizes directives names - using camelCase in the directive and dash seperated (usually) since html isn't case sensitive, in the template.

    so where you need to call the directive namedsuperMan with:

    <super-man></super-man>
    

    Here is a working Demo

    0 讨论(0)
  • 2020-12-16 21:41

    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).

    The normalization process is as follows:

    Strip x- and data- from the front of the element/attributes. Convert the :, -, or _-delimited name to camelCase.

    https://docs.angularjs.org/guide/directive

    You should have a camelCase name for your directive: eg superMan, and use one of the following syntax to call your directive, as HTML is case-insensitive:

    <super-man></super-man>
    <super_man></super_man>
    <super:man></super:man>
    <SuPer_man></sUpEr_mAn> //HTML is case Insensitive
    

    Demo: http://jsfiddle.net/QUP97/3/

    0 讨论(0)
  • 2020-12-16 21:53

    When you declare your directive you used the name SuperMan, however this is wrong. You should use superMan as that will be translated to super-man as the element.

    Any capital letter in the directive name will translate to a hyphen, as capital letters are not used in elements. For example myDirective will translate to my-directive.

    As mentioned by others, AngularJS uses normalisation the following normalisation rules:

    Strip x- and data- from the front of the element/attributes. Convert the :, -, or _-delimited name to camelCase.

    JavaScript:

    var app = angular.module('SuperHero',[]);
    app.directive('superMan',function(){
        return{
            restrict:'E',
            template: '<div>Hello fromt Directive</div>'
        }
    });
    

    HTML:

    <div ng-app="SuperHero">
        <super-man></super-man>
    </div>
    

    I updated your fiddle to match the correct syntax here jsfiddle.

    0 讨论(0)
提交回复
热议问题