javascript - AngularJS 指令 : Take a HTML attribute as a string, 用作字典键

标签 javascript html angularjs

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

(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 作为模板的输出。

根据我所读到的内容,隔离作用域的使用对 Controller 来说效果很差,并且可能是问题所在,但我很难让我的调试器向我展示任何与此相关的有用信息。有没有办法让这项工作发挥作用,或者我应该考虑以不同的方式设计它?

最佳答案

如果您也将方程传递到指令范围,您就可以访问它们:

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

关于javascript - AngularJS 指令 : Take a HTML attribute as a string, 用作字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28042928/

相关文章:

javascript - 在 > 32 位整数上使用按位运算符

javascript - backbone.js & raphäel.js/Backbone View <-> Raphäel 对象

JavaScript:如何清除我的自定义键盘映射并使用默认键盘映射

angularjs - Angular POST 到 Web API 不传递数据

javascript - 在 ES6 中将纯类注入(inject) angular 1.x 应用程序的正确方法

javascript - 如何将 jQuery UI 自动完成链接到多个输入元素?

javascript - 在 ckeditor 中插入 html 会导致语法错误(laravel)

javascript - Angular/Jasmine : spying on method passed to $rootScope. $on 带和不带匿名函数包装器

javascript - Silverlight 没有 html/css/javascript?

php - 包含 2 列的框和固定文本长度以匹配列宽