我想制作一个方程式标签,并使用标签属性来查找要使用的方程式。为此,我有以下应用程序:
(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/