【问题标题】:AngularJS directives misunderstandingAngularJS 指令的误解
【发布时间】:2016-08-23 05:32:16
【问题描述】:

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

我尝试了一些不同的方法:

  • <app-header> & <div=app-header>
  • 将 templateUrl 更改为模板:“测试标头”
  • 链接指令和 app.directive

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

【问题讨论】:

  • 问题或问题描述会有所帮助。到目前为止,这主要是一个声明。

标签: javascript angularjs angular-directive


【解决方案1】:

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

总之改变

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

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

【讨论】:

    【解决方案2】:

    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>
    

    请注意,上述内容仅适用于“标题”一词 - 您可能需要某种方式来定义不同的标题,对吧?

    .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> 
    

    这样,指令是可重用的。

    【讨论】:

    • 感谢您的快速回复!我没有收到任何错误,但是当我加载服务器时我仍然看不到标题:( 当我检查元素时,我看到 &lt;app-header&gt;&lt;/app-header&gt;== $0
    • 查看 Dustin 的回复 - 他是对的,没有它就行不通。我编辑了我的答案以解释他所说的话。
    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多