2017-02-15 62 views
1

我想創建一個簡單的自定義指令,我遇到了這個問題。 當我在我的html文件中指定<div my-info></div>指令時,它正在工作,但是當我指定爲<my-info></my-info>時,它不起作用。指令名稱作爲標記不起作用

我app.js文件

app.directive('myInfo', function() { 
return { 
     template:"<h3>My info directive</h3>" };}); 

我的HTML文件

<body ng-app="app"> 
<div ng-controller="emp"> 
    <div my-info></div> <!-- This is working--> 
    <my-info></my-info> <!-- This is not working --> 
</div> 

回答

1
app.directive('myInfo', function() { 
    return { 
     restrict: 'EA', // can be applied as element or attribute 
     template:"<h3>My info directive</h3>" 
    }; 
}); 

默認情況下,指令只能爲屬性(A)被應用。確保您添加restrict字段並指定它也可以作爲元素應用。

angular.module('app', []) 
 
.directive('myInfo', function() { 
 
    return { 
 
     restrict: 'EA', 
 
     template:"<h3>My info directive</h3>" 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<body ng-app="app"> 
 
<div> 
 
    <div my-info></div> 
 
    <my-info></my-info> 
 
</div> 
 
</div>

有關更多信息,請參見https://docs.angularjs.org/guide/directive

+0

當你創建一個指令,它制約因素只有默認的屬性,並添加限制屬性。爲了創建由類名/註釋觸發的指令,您需要使用restrict選項。 –

+0

@arunkumartalla是你評論意味着這個職位? – Chanthu

+0

no @Chanthu for this'默認指令只能用作屬性(A)。 ' –

1

嘗試:

app.directive('myInfo', function() { 
    return { 
      restrict: 'E', 
      template:"<h3>My info directive</h3>" };}); 

From angular documentation

的限制選項通常設置爲:

'A' - 只匹配屬性名稱
'E' - 只匹配元素名稱
'C' - 只匹配類名
'M' - 只匹配評論

您也可以將它像restrict: 'EA'

1
<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Angular</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 

    </head> 
<body ng-app="app"> 
<div ng-controller="emp"> 
    <div my-info></div> <!-- This is working--> 
    <my-info></my-info> <!-- This is working --> 
</div> 
<script type="text/javascript"> 
angular 
.module('app', []) 
.controller('emp', function() { 

}).directive('myInfo', function() { 
return { 
     template:"<h3>My info directive</h3>" 
    }; 
}); 
</script> 
    </body> 
</html> 

其實當你與角指令工作

app.directive('myInfo', function() { 
    return { 
      restrict: 'E', 
      template:"<h3>My info directive</h3>" 
}; 
}); 

上面的代碼將讓retrict你的指令爲唯一元素,如果你想和你需要添加屬性發揮「retrict:A」,如果兩個「retrict:EA」

1

你可以調用指令通過使用:

  • 屬性(A)<div my-info></div>
  • 元素(E)<my-info></my-info>
  • 類(C)<div class="my-info"></div>
  • 評論(M)<!-- directive: my-info -->

在指令