计算传递给Angular指令的对象中的字符串表达式

Evaluate expressions that are strings in an object that you pass to an Angular directive

本文关键字:对象 字符串 表达式 指令 Angular 计算      更新时间:2023-09-26

如何计算传递给指令的对象中的字符串表达式?我已经看了以下答案,但无法使其发挥作用:

从数据库编译动态HTML字符串

AngularJS 中动态添加指令

如何在自定义指令中获取评估属性

切入正题,代码如下:

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>

绑定属性本身有一个字符串,恰好是角度表达式{{units}}。但angular并不知道它,就它而言,它只是要写入DOM的另一个字符串值。您可能希望使用$interpolate服务来展开字符串中的任何插值,并用其值替换字符串中的插值。例如:

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