【问题标题】:Angular JS Custom Directive not working as element tagAngular JS 自定义指令不能用作元素标记
【发布时间】:2017-08-27 02:41:00
【问题描述】:

我正在玩一些基本的 Angular JS 东西。我以为我非常了解自定义指令,但如果我将它们用作元素属性,我只能让它们显示在模板中。而且我不想使用 cmets 或类名,因为它们不是最佳实践。根据文档和其他来源,这些指令应该作为元素和元素属性工作。

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

【问题讨论】:

  • 您的控制台中是否存在跨源错误?....如果是,您需要使用 Mamp 之类的东西来提供 html 模板
  • @PatoSalazar,这个问题与跨域有什么关系?
  • 我试图在 Chrome 中加载他的代码,但我得到了那个错误。如果我使用 Mamp 加载网站,则代码有效
  • 确切地说是XMLHttpRequest cannot load file:///Applications/MAMP/htdocs/personal%20project/stackoverflow/secondDirective.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
  • @PatoSalazar,当然,您会收到该错误,因为您尝试加载不存在的 /scripts/directives/secondDirective.j

标签: javascript html angularjs angularjs-directive


【解决方案1】:

在 Angular 1.2x 中,您必须将限制值设置为包含“E”,因为它默认不包含。

.directive('secondDirective', function() {
    return {
        restrict: 'EA',
        template: '<div><h2>Esta Aqui!</h2></div>'
    }
})

升级到较新的 Angular 版本,“EA”被设置为默认值。

【讨论】:

  • 我认为默认值为EA,这意味着元素标签和属性名称都可以调用指令。
  • @TomSarduy 它的版本大于 1.2x
  • 看看复制他的代码...确保文件的路径正常,并使用mamp打开它们...问题的代码有效...这是一个跨源问题跨度>
  • @Ace 你是对的...我运行的是 1.2.13 版本,需要restrict: 'EA。但是如果我不使用 Mamp,我仍然会收到跨源错误...
  • @PatoSalazar,与 CORS 无关的问题,因为指令是使用属性呈现的。艾斯,好球! +1
【解决方案2】:

[更新] 用户@Ace 指出,您可能正在使用旧版本的 Angular。您需要在返回时声明restrict: 'EA' 才能使其工作。

另外,以防万一,如果您运行代码并在控制台中收到跨源错误。这里AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https 说这是因为你试图从浏览器加载一个 html 模板。你需要使用 MAMP 之类的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2014-07-23
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多