【发布时间】:2017-03-23 14:12:46
【问题描述】:
例如,我有一些默认行没有删除按钮的 ng-repeat,我想添加可以删除的新行。删除功能在添加的行中不起作用。我知道我可以通过使用指令和 $compile 来解决这个问题,但我不明白如何将它与 ng-repeat 一起使用。
HTML
<body ng-app="TestApp" ng-controller="Test">
<ul>
<li ng-repeat="o in array">
<div id="name">{{ o.name }}</div>
<div id="remove" ng-bind-html="o.remove"></div>
</li>
</ul>
<fieldset>
<input ng-model="inputname">
<button ng-click="addRow(inputname)">Add row</button>
</fieldset>
</body>
JS
angular.module('TestApp', []).controller("Test", function($scope, $sce) {
$scope.array = [{name: "Test1"},{name: "Test2"},{name: "Test3"},{name: "Test4"}]
$scope.addRow = function(name){
var a = { name: name,
remove: $sce.trustAsHtml("<button ng-click='removeRow($index)' </button>")
}
$scope.array.push(a)}
$scope.remove = function(index) {
$scope.array.splice(index, 1)}
})
【问题讨论】:
-
remove中是否会有不同的 HTML,或者为什么要将其添加为string而不是模板? -
是的,正如@Arg0n 所说,更简单的解决方案似乎是将
<button>包含在模板本身中,或者如果需要以某种方式对其进行参数化,则使其成为自己的指令。
标签: javascript angularjs angularjs-ng-repeat