如何计算传递给指令的对象中的字符串表达式?我已经查看了以下答案,但无法解决此问题:
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对象中的{{units}}。我尝试过使用$ 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>
答案 0 :(得分:2)
绑定属性本身有一个恰好是角度表达式{{units}}
的字符串。但是角度不知道它,只要它担心它只是写入DOM的另一个字符串值。您可能希望使用$interpolate
service来扩展字符串中的任何插值,并将其替换为字符串中的值。例如:
interpolate("ABC {{units}}DEF")(scopeOrAnyObject)
将返回“ABC VALUEOFUNITSDEF”
在你的情况下,你可以做一个简化/简约的例子:
scope.getValue = function(val){
return angular.isString(val) ? $interpolate(val)(scope) : val;
}
并将其用作:
<td data-ng-repeat="val in column">{{getValue(val)}}</td>
<强> Plnkr 强>