Ellie Crome Ellie Crome - 3 months ago 19
AngularJS Question

AngularJS directives misunderstanding

I am trying to create a basic app with a header & main view, using directives. Initially I had the directive in a separate file, but have moved it into app.js to eliminate a problem.

I have tried a few different things:


  • <app-header>
    &
    <div=app-header>

  • Changing templateUrl to template:"Test header"

  • Chaining the directive and app.directive



My index.html:

<!DOCTYPE html>
<html lang="en" ng-app="simpleLoginApp">

<head>
<meta charset="utf-8" />
<title> Simple Login </title>
</head>

<body>
<div app-header></div>
<main role="main" ng-view></main>

<script src="resources/angular/angular.min.js"></script>
<script src="resources/angular-route/angular-route.js"></script>
<script src="app.js"></script>
</body>

</html>


My app.js:

var app = angular.module('simpleLoginApp', ['ngRoute'])

.directive('app-header', function() {
return {
templateUrl: '/header/header.html'
};
})

.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: '/login/login.html',
controller: 'LoginCtrl'
})
}]);


Header.html

<header>
<h1>HEADER</h1>
</header>

Answer

The problem is how you register your directive. When defining a directive, you should use camel case, e.g. appHeader instead of app-header. When using it in a template you should use the dashes as you've done. You can see the documentation here under the Normalization heading

In short change

.directive('app-header', function() {
  return {
    templateUrl: '/header/header.html'
  };
})

to

.directive('appHeader', function() {
  return {
    templateUrl: '/header/header.html'
  };
})