簡體   English   中英

AngularJS指令:將HTML屬性作為字符串,用作字典鍵

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

我想制作一個方程式標簽,並使用label屬性來查找要使用的方程式。 為此,我有以下應用程序:

(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>

和eqnEquation.html:

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

您從未將doc綁定到指令中的作用域。 注入方程式服務,並在范圍內將其稱為doc,然后它將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM