【问题标题】:Directives are not working in Angular 1.2.20指令在 Angular 1.2.20 中不起作用
【发布时间】:2014-10-08 02:44:21
【问题描述】:

a previous question 中,我在让复杂的小部件正常工作时遇到问题。

在清醒的头脑中醒来后,我决定我应该从健全性检查开始:我可以获得一个基本指令以正常工作吗?鉴于我过去写过指令,我没有预见到困难。

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'
  }
);

显然,这不是一个理智的案例。我正在使用 Angular 1.2.20,但显然,具有硬编码模板的非常基本的指令或具有对硬编码模板的 URL 引用的基本指令都不能正常工作。由于这是一个非常基本的案例,我的问题:我做错了什么吗?我应该在 Angular 的 GitHub 项目上打开一个错误吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您的问题很简单:指令名称的第一个字母必须小写。 例如,不要使用SecondTestDirective,而是使用secondTestDirective

    在匹配指令时,Angular 会从元素/属性名称中去除前缀​​ x- 或 data-。然后它将 - 或 : 分隔的字符串转换为 camelCase 并与注册的指令匹配。这就是我们在 HTML 中使用 secondTestDirective 指令作为 second-test-directive 的原因。

    【讨论】:

    • 确实是+1。由于我周围发生的一些其他研究,我注意到 x- 和 data- 被剥离,camelCase 被转换为蛇形,但这可能有助于将来关注这个问题的新手站稳脚跟。好答案!
    • 谢谢...这是一篇关于 AngularJS 指令的精彩文章:sitepoint.com/practical-guide-angularjs-directives
    【解决方案2】:

    您的代码有几个问题,这是它的修复版本:

    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

    出错的地方:

    1. 指令的名称应采用驼峰式格式(第一个字符应为小写)
    2. 第二个指令没有返回对象
    3. 如果要将指令用作元素,则应在 restrict 属性中指定。

    【讨论】:

    • @AndrewGray 另外,第二个指令没有返回对象,我刚刚更新了我的答案。
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2019-03-26
    • 2018-09-16
    • 2015-03-30
    • 2018-11-09
    相关资源
    最近更新 更多