簡體   English   中英

Angular JS自定義指令無法用作元素標簽

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM