javascript - 在 ng-bind 内容之前添加 html 元素

标签 javascript angularjs

我有一个由 ng-repeat 渲染的表,并使用 ng-bind 绑定(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

最佳答案

您不希望 Controller 了解有关 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/

相关文章:

javascript - 使用 JQuery 解析 XML(需要逻辑帮助)

javascript - AngularJS Controller 不是一个函数,未定义

javascript - 如何将当前日期增加 20 分钟?

javascript - 一次单击即可实现两个功能 - Javascript

javascript - 在cherrypy中在python和javascript之间共享变量信息

javascript - 从服务获取变量到 Controller

angularjs - 如何部署 yeoman angular-fullstack 项目?

javascript - ExtJS - 将日期值发布为 Unix 时间戳

javascript - 设置 AngularJS 范围标签的值

Javascript:将对象从一个数组移动到另一个数组:最佳方法?