[英]Angular JS Custom Directive not working as element tag
我在玩基本的Angular JS东西。 我以为我很了解自定义指令,但是如果将它们用作元素属性,我只能让它们显示在模板中。 而且我不想使用注释或类名,因为它们不是最佳实践。 基于文档和其他来源,这些指令应作为元素和元素属性工作。
在index
您会看到我两次声明了指令-在顶部的块中作为属性(有效),在底部的块中作为元素(无效)。 我已经深陷这个问题了。 非常感谢任何见解。
Index.html
<head>
<title>Test App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='styles/css/style.css' rel='stylesheet' type="text/css">
<script src="vendor/angular_1.2.13/angular.min.js"></script>
</head>
<body ng-app="testApp" class="app__body">
<div class="body__inner">
<header>
<h1>My New Test App</h1>
</header>
<div first-directive></div>
<div second-directive></div>
<first-directive></first-directive>
<second-directive></second-directive>
</div>
<script src="scripts/all-in-one.js" type="text/javascript"></script>
</body>
all-in-one.js
'use strict';
angular.module('testApp', [])
.directive('firstDirective', function() {
return {
template: 'Hello World'
}
})
.directive('secondDirective', function() {
return {
templateUrl: '/scripts/directives/secondDirective.js'
}
})
.controller('firstCtrl', function($scope) {
$scope.message = "Hola Amigos!"
})
secondDirective.js
<div>
<h2>Esta Aqui!</h2>
</div>
在angular 1.2x中,您必须将限制值设置为包括“ E”,因为默认情况下不包括该值。
.directive('secondDirective', function() {
return {
restrict: 'EA',
template: '<div><h2>Esta Aqui!</h2></div>'
}
})
升级到较新的角度版本,将“ EA”设置为默认值。
[更新]用户@Ace指出,您可能正在使用旧版本的Angular。 您需要在返回时声明restrict: 'EA'
以使其起作用。
另外,以防万一,如果您运行代码并在控制台中出现跨源错误。 此处AngularJS错误:协议方案仅支持跨源请求:http,数据,chrome扩展名,https表示这是因为您试图从浏览器加载html模板。 您需要使用MAMP之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.