【问题标题】:How to use an AngularjS View (.html file) without using it's tags如何在不使用标签的情况下使用 AngularjS 视图(.html 文件)
【发布时间】:2018-02-16 00:08:01
【问题描述】:

在一个大型 AngularJS 应用程序中,我有一个新的 HTML 模板文件和一个控制器,我想使用这个临时视图构建设计师给我的布局,因为我希望能够调用一些来自 $scope 对象的数据。

我还为它创建了一条新路线,以便我有一个干净的工作空间。

但我不想将它包含在主 index.html 文件中,如下所示:

<my-new-template></my-new-template>

我只想开始使用它,而不必在任何地方包含这个 HTML 元素,这可能吗?这是目前的控制器:

.directive('portfolio', [
function () {
        return {
            templateUrl: "views/temporary-view.html",
            scope: {
                data: "="
            },

            link: function (scope, element, attrs, ctrl) {                  
                scope.stuff = 'stuff';                  
            }
        };
    }])

观点:

<nav class="portfolio-view">
       {{stuff}}
</nav>

感谢您帮助像我这样的菜鸟! :)

【问题讨论】:

  • 很遗憾看到您已经投了一些反对票。如果投反对票的人可以为您留下评论,那就太好了。基本上,你的问题不清楚。例如,您将指令代码显示为控制器代码。也许您需要重新表述整个问题,以便获得社区的回复。
  • 我想我明白你在说什么,换句话说,使用 .controller 而不是 .directive?

标签: angularjs angular-routing angular-controller angular-template


【解决方案1】:

在您的指令中,您可以更改 restrict 选项以更改指令在 HTML 中的调用方式。有 4 个选项。我在AngularJS documentation for directives 中找到了这个:

restrict
String of subset of EACM which restricts the directive to a specific directive declaration style. If omitted, the defaults (elements and attributes) are used.

E - Element name (default): <my-directive></my-directive>
A - Attribute (default): <div my-directive="exp"></div>
C - Class: <div class="my-directive: exp;"></div>
M - Comment: <!-- directive: my-directive exp -->

默认情况下,它使用EA,因此作为元素(您不想在 HTML 中调用它的方式)或属性。

如果您希望将其更改为例如类,则将指令定义更改为:

.directive('portfolio', [
function () {
        return {
            restrict: 'C',
            templateUrl: "views/temporary-view.html",
            scope: {
                data: "="
            },

            link: function (scope, element, attrs, ctrl) {                  
                scope.stuff = 'stuff';                  
            }
        };
    }])

你可以这样称呼它:

&lt;div class="portfolio"&gt;&lt;/div&gt;

我认为这就是您的意思,希望对您有所帮助!

【讨论】:

    【解决方案2】:

    所以我只是将 .directive 更改为 .controller 并将其与应用程序中的其他控制器而不是指令一起发布...我想我对此感到困惑!

    .controller('PortfolioView', ["$scope",
        function ($scope) {
            $scope.stuff = 'stuff'; 
        }])
    

    【讨论】:

      猜你喜欢
      • 2014-09-24
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      相关资源
      最近更新 更多