Reputation: 350
I'm playing around with basic Angular JS stuff. I thought I knew custom directives pretty well but I'm only able to get them to show up in the template if I use them as element attributes. And I'm not wanting to use comments or class names as those are not best practices. Based on documentation and other sources these directives SHOULD work as an element AND an element attribute.
In my index
you'll see that I'm declaring my directives twice -- in the top block as attributes (which work) and the bottom block as elements (which don't work). I'm hours deep into this problem. Any insight is tremendously appreciated.
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>
Upvotes: 1
Views: 1221
Reputation: 969
In angular 1.2x you have to set the restrict value to include 'E' as its not included by default.
.directive('secondDirective', function() {
return {
restrict: 'EA',
template: '<div><h2>Esta Aqui!</h2></div>'
}
})
Upgrading to a newer angular version, 'EA' is set as a default value.
Upvotes: 6
Reputation: 1477
[Update]
A user @Ace points out, you might be using and old version of Angular. You need to declare restrict: 'EA'
when you return to make it work.
Also, and just in case, if you ran your code and get a cross origin error in the console. Here AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https says it is because you are trying to load an html template from the browser. You need to use something like MAMP.
Upvotes: -1