AngularJS指令误解

AngularJS directives misunderstanding

我正在尝试使用指令创建一个带有页眉和主视图的基本应用程序。最初我将该指令放在一个单独的文件中,但已将其移至 app.js 以消除问题。

我尝试了几种不同的方法:

我的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>

我的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>

Header.html 只需:

<h1>HEADER</h1> 

您的指令必须是:

.directive('appHeader', function() {
  return {
    restrict: 'E', //This will make your directive work as an element  
    templateUrl: '/header/header.html'
  };
})

然后您只需将您的指令作为元素包含在代码中:

<app-header></app-header>

请注意,以上仅适用于单词 "Header" - 您可能需要某种方式来定义不同的 headers,对吗?

.directive('appHeader', function() {
  return {
    scope: {
        headerText: '='; 
    }
    restrict: 'E', //This will make your directive work as an element  
    templateUrl: '/header/header.html'
  };
})

然后在你的代码中:

<app-header header-text="lol this is the content of my header ^_^"></app-header> 

这样,指令就可以重用了。

问题在于您如何注册指令。定义指令时,您应该使用驼峰式大小写,例如appHeader 而不是 app-header。在模板中使用它时,您应该像以前一样使用破折号。您可以在规范化标题

下查看文档 here

简而言之

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

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