【问题标题】:Access attrs in AngularJS directive templateUrl在 AngularJS 指令 templateUrl 中访问 attrs
【发布时间】:2015-06-05 17:54:22
【问题描述】:

我有一个问题,因为我还没有 100% 理解 AngularJS 指令。我有这样的指令,

在我的 HTML 中:

<div my-directive="Hello World"></div>

在我的指令 JS 文件中:

.directive('myDirective', [function ( ) {
        return {
            restrict: 'A',
            priority: 100,
            templateUrl: 'views/templates/my-directive.html',
            link: function (scope, element, attrs) {
                // I wish to pass attrs.myDirective to the templateUrl
            }
        };
    }]);

在我的 templateUrl 'views/templates/my-directive.html' 中:

<h1> {{ attrs.myDirective }} </h1>

显然这确实有效,我的指令值被传递给链接函数但没有传递给 templateUrl,我怎样才能在我的 templateUrl 中输出值?愚蠢的问题我知道,但我不确定实现它的最佳方法是什么?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您可以简单地将这个值分配给范围变量。

      scope.myDirective=attrs.myDirective
    
    app.directive('myDirective', [function ( ) {
            return {
                restrict: 'A',
                priority: 100,
                templateUrl: 'my-directive.html',
                link: function (scope, element, attrs) {
                  scope.myDirective=attrs.myDirective
                    // I wish to pass attrs.myDirective to the templateUrl
                }
            };
        }]);
    

    Plunker

    【讨论】:

    • 我最初是这样做的并且它有效,但是我不确定是否要使用编译功能将 attr this 传递给 templateUrl
    • 这里不需要编译,直到你有动态模板:)
    猜你喜欢
    • 2023-03-25
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多