如何计算传递给指令的对象中的字符串表达式?我看了下面的答案,但无法让它工作:
Compiling dynamic HTML strings from database
Dynamically add directive in AngularJS
How to get evaluated attributes inside a custom directive
切入追逐,这里是代码:
http://plnkr.co/edit/b2FblYElVGnzZRri34e0?p=preview
这是我试图评估的reportData对象中的{} . 我尝试过使用$ compile服务,但无法使用它 . 提前致谢!
.js文件:
var App = angular.module('plunker', [])
.controller("testCtrl", function($scope){
$scope.units = "Houses";
mockreport = {"COLUMNS":["People","Units"],"DATA":[[101,"{{units}}"],[100,"test 2"]]};
$scope.reportData = mockreport;
})
.directive('testdirective', function($compile,$parse,$interpolate){
return{
restrict : 'E',
scope:{
units:'@',
reportData:'='
},
templateUrl:'table.html',
link: function (scope, $el, attrs) {
curHtml = $el.html();
recompiledHtml = $compile(curHtml)(scope);
//$el.html('');
//$el.append(recompiledHtml);
}
};
});
index.html的:
<div data-ng-controller="testCtrl">
<div class="panel panel-default">
<testdirective report-data="reportData" units="{{units}}">
</testdirective>
</div>
</div>
table.html:
<h4>units: {{units}}</h4>
<table>
<thead>
<tr>
<th data-ng-repeat="header in reportData.COLUMNS" data-ng-class="header">{{header}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="column in reportData.DATA">
<td data-ng-repeat="val in column">{{val}}</td>
</tr>
</tbody>
</table>
1 回答
你有绑定属性本身有一个字符串恰好是一个角度表达式
{{units}}
. 但是角度不知道它,只要它涉及它只是写入DOM的另一个字符串值 . 您可能希望使用$interpolate service扩展字符串中的任何插值,并将其替换为字符串中的值 . 例如:interpolate("ABC {{units}}DEF")(scopeOrAnyObject)
将返回"ABC VALUEOFUNITSDEF"在你的情况下,你可以做一个简化/极简主义的例子:
并用它作为:
Plnkr