调用另一个自定义指令的角度自定义指令

Angular custom directive calling another custom directive

本文关键字:自定义 指令 调用 另一个      更新时间:2023-09-26

我正在开发一个角度框架,用户可以在其中使用自定义指令配置页眉,菜单,页脚和选定页面。要完成此要求,我一度需要以下内容。我在网上看到过例子,但并没有很好地解释它。

要求是第一个自定义指令的 templateUrl 应替换为应调用另一个自定义指令的模板属性。

以下带有模板 URL 的代码工作正常。

angular.module("app",[]);
angular.module("app").controller("productController", ['$scope', function ($scope) {

}]);
angular.module("app").directive("tmHtml", function () {
    return {
        transclude: false,
        scope: {
        },
        controller: "productController",
        templateUrl: "/templates/HideShow.html"
    };
});

但是,当我按如下方式更改上面的代码时。我正在进行更改,以便我的自定义指令 tmHtml 调用另一个自定义指令。

 angular.module("app").directive("tmHtml", function () {
        return {
            transclude: false,
            scope: {
            },
            controller: "productController",
         template: ``<hideShow></hideShow>``
        };
    });

隐藏显示的新指令编写如下

angular.module("app").directive("hideShow", function () {
    return {
        tempateUrl: "/templates/HideShow.html"
    };
});

它不起作用。我知道我在这里错过了一些东西。我找不到。感谢帮助

工作代码:

var app = angular.module('plunker', []);
app.controller('productController', function($scope) {
});
app.directive("hideShow", function() {
  return {
    templateUrl: "hideshow.html"
  };
});

app.directive("tmHtml", function() {
  return {
    transclude: false,
    scope: {},
    controller: "productController",
    template: "<hide-show></hide-show>"
  };
});

问题在于hideShow指令中templateUrl的拼写。

演示 : http://plnkr.co/edit/TaznOeNQ7dM9lyFgqwCL?p=preview

尝试使用 controllerAs 定义控制器:

angular.module("app").directive("tmHtml", function () {
    return {
        transclude: false,
        scope: {
        },
        controllerAs: "productController",
        templateUrl: "/templates/HideShow.html"
    };
});
 angular.module("app").directive("tmHtml", function () {
        return {
            transclude: false,
            scope: {
            },
            controller: "productController",
         template: ``<hideShow></hideShow>``
        };
    });

必须替换为

 angular.module("app").directive("tmHtml", function () {
        return {
            transclude: false,
            scope: {
            },
            controller: "productController",
         template: "<hide-show></hide-show>"
        };
    });

在属性 template 下,添加 Html。因此,您仍然必须在那里使用蛇形外壳,就像在 HTML 文件中一样

您的第一个指令可能具有您观察到的最终作用域属性。

然后它可能会包装第二个指令。如果需要,您的指令可以作为父母和孩子进行沟通。