簡體   English   中英

指令在Angular 1.2.20中不起作用

[英]Directives are not working in Angular 1.2.20

在上一個問題中 ,我遇到了使復雜的小部件無法正常工作的問題。

醒了醒后,我決定應該從健全性檢查入手:我能否獲得基本的指示以正常工作? 鑒於我過去曾經寫過指令,因此我沒有遇到任何困難。

這是我寫的基本代碼,只有兩個非常基本的用例。

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項目上打開錯誤嗎?

您的問題很簡單:偽指令名稱的首字母必須小寫。 例如,而不是SecondTestDirective使用secondTestDirective

在匹配指令時,Angular從元素/屬性名稱中刪除前綴x-或data-。 然后,它將-或:分隔的字符串轉換為camelCase並與注冊的指令匹配。 這就是為什么我們在HTML中使用secondTestDirective指令作為second-test-directive的原因。

您的代碼有幾處錯誤,這是它的固定版本:

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

錯誤的事情:

  1. 指令名稱應采用駝峰格式(第一個字符應為小寫)
  2. 第二個指令沒有返回對象
  3. 如果要將指令用作元素,則應在restrict屬性中指定該指令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM