我有一个由ng-repeat渲染的表,并使用ng-bind绑定到模型。我想根据条件在第一列上添加一个html元素。我怎样才能做到这一点?

<!doctype html>
<html ng-app="plunker">

<head>
<script data-require="angular.js@*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<div ng:controller="MainCtrl">

<table border="1">
  <thead style="font-weight: bold;">
    <tr>
      <th class="text-right" ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind="column.id"></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in rows">
      <td ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind="formatValue(row[column.id], column.id == 'Value1')"></td>
    </tr>
  </tbody>
</table>
</div>




<script>
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $filter) {



  $scope.formatValue = function(value, addIcon) {

    if (addIcon) {
      var htmlElement = '<span>This is a SPAN</span>'

      value = htmlElement + value;
    }

    return value;
  }


  $scope.columnsTest = [{
    id: 'Value1',
    checked: true
  }, {
    id: 'Value2',
    checked: true
  }, {
    id: 'Value3',
    checked: true
  }];


  $scope.rows = [{
    id: 1,
    "Value1": 911,
    "Value2": 20,
    "Value3": 20
  }, {
    id: 2,
    "Value1": 200,
    "Value2": 20,
    "Value3": 20
  }];



});







我希望将html元素呈现在值之前。我试过使用$ scope,但是没有用。跨度仍以文本形式显示。

这是一个Plunker

最佳答案

您不希望控制器对HTML有所了解。所以不要那样做。而是使用ngIf指令有条件地添加跨度:

<tr ng-repeat="row in rows">
    <td ng-repeat="column in columnsTest" ng-if="column.checked">
        <span ng-if="column.id == 'Value1'">ICON</span>
        {{ row[column.id] }}
    </td>
</tr>


演示:http://plnkr.co/edit/oUtzD2lQoF29PyOgs2k4?p=info

关于javascript - 在ng-bind中的内容之前添加html元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34420436/

10-17 02:28