gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:32:43 25 4
gpt4 key购买 nike

我有一个由 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com