AngularJS指令:将HTML属性作为字符串,用作字典键

AngularJS Directives: Take a HTML attribute as a string, used as a dictionary key

本文关键字:字符串 字典 AngularJS HTML 属性 指令      更新时间:2023-09-26

>我想做一个方程标签,并使用标签属性来查找要使用的公式。为此,我有以下应用程序:

(function(){
    var app = angular.module('mathDocument', []);
    app.directive('equation', function(){
        return {
            restrict: 'E',
            scope: {
                label: '@label'}, 
            templateUrl: 'eqnElement.html',
        };
    });
    app.controller("DocumentController", function(){
        this.equations = {
                "mainresult": { labeled: true,
                                label: 'mainresult',
                                body: 'e^{i''pi} = -1',
                              }
        };
    });
})();

以及 eqnElement 中的一个模板.html:

<body ng-controller="DocumentController as doc">
    <div>
        {{ doc.equations[label].body }}
    </div>
</body>

但是,当我尝试使用公式标签时,

<equation label="mainresult"></equation>

我最终什么也得不到。如果我改用{{ label }},我最终会看到mainresult作为模板的输出。

从我所读到的内容来看,隔离范围的使用与控制器一起玩得很糟糕,可能是问题所在,但我很难让我的调试器向我展示任何有用的东西。有没有办法做到这一点,或者我应该考虑以不同的方式设计它?

如果将equations也传递给指令范围,则可以访问它们:

(function(){
    var app = angular.module('mathDocument', []);
    app.directive('equation', function(){
        return {
            restrict: 'E',
            scope: {
                label: '@label',
                equations: '='
            }, 
            templateUrl: 'eqnElement.html',
        };
    });
    app.controller("DocumentController", function($scope){
        $scope.equations = {
                "mainresult": { labeled: true,
                                label: 'mainresult',
                                body: 'e^{i''pi} = -1',
                              }
        };
    });
})();

调用指令时:

<equation equations="equations" label="mainresult"></equation>

方程.html:

<div>
    {{ equations[label].body }}
</div>

您从未将 doc 绑定到指令中的范围。注入方程服务并在作用域中调用它 doc,然后它就会起作用。