2017-02-15 64 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 -->

在指令