javascript - AngularJS 指令通信和页面模板 - 内部指令不起作用

标签 javascript html angularjs angularjs-directive

指令通信有一些问题,尤其是内部和外部自定义标签。

所以,我有以下 HTML 代码:

<html>
<title>Directives</title>
<head lang="en">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js" type="text/javascript"></script>
<script src="main.js"></script>
</head>
<body ng-app="app">
    <outer>
        <inner></inner>
    </outer>
</body>
</html>

我的 AngularJS 指令有以下 JavaScript 代码:

var app = angular.module("app", []);

app.directive("outer", function() {
    return {
        template: "<div>This is outer message</div>",
        restrict: "E",
        replace: false,
        controller: function() {
            this.say = function(message) {
                console.log(message);
            }
        }
    }
});

app.directive("inner", function() {
    return {
        restrict: "E",
        require: "^outer",
        replace: false,
        controller: function($scope) {},
        link: function(scope, element, attrs, outerCtrl) {
            outerCtrl.say("This is inner message");
        }
    }
});

看起来很简单。我想在屏幕上显示一条消息,在控制台记录器上显示另一条消息。但是第二个直到我发表评论才出现 template: "<div>This is outer message</div>"线!我想问题与页面呈现(链接和编译功能)有关。实际上我对它很困惑,我无法修复这个错误。 谁能帮帮我?

最佳答案

如果您提供模板,它将替换<outer>的内容(replace 选项仅控制是否也替换 <outer> 标签)。

因此,<inner>指令不再链接。如果您想在链接内部标签的同时提供模板。您需要使用包含:

app.directive("outer", function() {
    return {
        template: "<div>This is outer message <div ng-transclude></div></div>",
        restrict: "E",
        replace: false,
        transclude: true,
        controller: function() {
            this.say = function(message) {
                console.log(message);
            }
        }
    }
});

这将在带有 ng-transclude 的 div 内部插入 inner .

关于javascript - AngularJS 指令通信和页面模板 - 内部指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275293/

相关文章:

javascript - 使用 ngif 时 ngclass 的奇怪行为

javascript - 在动态创建的 HTML 表中调用 PHP 函数

angularjs - 无法通过 npm 安装 gulp-jshint

angularjs - 无法取消 $interval 返回的链式 promise

javascript - 如何通过单击按钮上传文件

javascript - 为什么 Array().slice 没有 "new"工作?

jquery - 多个文本字段时自动完成用户界面的 CSS 问题

javascript - HTML 无法识别 eventListeners

angularjs - 过滤器参数中的 Angular.js 插值

javascript - 我应该用哪种方法注入(inject)javascript? (stringByEvaluatingJavaScriptFromString)