简体   繁体   中英

Directives are not working in Angular 1.2.20

In a previous question , I was having problems getting a complex widget to properly work.

After waking up with a clear head, I decided that I should start with a sanity check: can I get a basic directive to properly work? Given that I have written directives in the past, I foresaw no difficulty.

This is the basic plunker I wrote, with only two very basic use cases.

app.directive('TestDirective',
  function () {
    return {
      template: '<strong>This is a test directive.</strong>'
    };
  }
);

app.directive('SecondTestDirective', 
  function () {
    templateUrl: 'directiveTest.html'
  }
);

This is not a sane case, apparently. I'm using Angular 1.2.20, but apparently, neither a very basic directive with a hardcoded template, or a basic directive with a URL reference to a hardcoded template, are working properly. As this is a very basic case, my question : am I doing anything wrong? Should I open a bug on Angular's GitHub project?

Your problem is simple: first letter of directive name must be lowercase. For example, instead of SecondTestDirective use secondTestDirective

While matching directives, Angular strips the prefix x- or data- from element/attribute names. Then it converts - or : delimited strings to camelCase and matches with the registered directives. That's why we have used the secondTestDirective directive as second-test-directive in the HTML.

There were several things wrong with your code, this is the fixed version of it:

app.directive('testDirective',
  function () {
    return {
      restrict: 'AE',
      template: '<strong>This is a test directive.</strong>'
    };
  }
);

app.directive('secondTestDirective', 
  function () {
    return{
      restrict: 'AE',
      templateUrl: 'directiveTest.html'
    }
  }
);

Example

Things that were wrong:

  1. The names of the directives should have a camel-case format (the first character should be lowercase)
  2. The second directive was not returning an object
  3. If you are going to use your directive as Elements, you should specify that in the restrict attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM