我正在尝试创建一个简单的自定义指令,我遇到了这个问题。
当我在我的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>
答案 0 :(得分: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>"
};
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
尝试:
app.directive('myInfo', function () {
return {
restrict: 'E',
template:"<h3>My info directive</h3>" };});
restrict选项通常设置为:
'A' - 仅匹配属性名称
'E' - 仅匹配元素名称
'C' - 仅匹配班级名称
'M' - 仅匹配评论
您也可以将其组合为restrict: 'EA'
答案 2 :(得分: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:A”,如果“retrict:EA”强>
答案 3 :(得分:1)
您可以使用以下方法调用指令:
- 属性(A)
<div my-info></div>
- 元素(E)
<my-info></my-info>
- Class(C)
<div class="my-info"></div>
- 评论(M)
<!-- directive: my-info -->
在指令
中添加restrict属性