Javascript 使用指令将trustAsHtml推到ng repeat
例如,我有一些不带删除按钮的默认行的ng repeat,我想添加可以删除的新行。删除函数在添加的行中不起作用。我知道我可以通过使用指令和$compile来解决这个问题,但我不知道如何使用ng repeat HTMLJavascript 使用指令将trustAsHtml推到ng repeat,javascript,angularjs,angularjs-ng-repeat,Javascript,Angularjs,Angularjs Ng Repeat,例如,我有一些不带删除按钮的默认行的ng repeat,我想添加可以删除的新行。删除函数在添加的行中不起作用。我知道我可以通过使用指令和$compile来解决这个问题,但我不知道如何使用ng repeat HTML {{o.name}} 添加行 JS angular.module('TestApp',[]).controller(“Test”),function($scope,$sce){ $scope.array=[{name:“Test1”},{name:“Test2”},{na
-
{{o.name}}
添加行
JS
angular.module('TestApp',[]).controller(“Test”),function($scope,$sce){
$scope.array=[{name:“Test1”},{name:“Test2”},{name:“Test3”},{name:“Test4”}]
$scope.addRow=函数(名称){
var a={name:name,
删除:$sce.trustAsHtml(“签出此链接,添加了编译模板指令,更新了plnkr:
在HTML中:
<ul>
<li ng-repeat="o in array"><div id="name">{{ o.name }}</div>
<!-- added compile-template -->
<div id="remove" ng-bind-html="o.remove" compile-template></div>
</li>
</ul>
remove
中是否会有不同的HTML,或者为什么要将其作为字符串添加到模板中而不是添加到模板中?是的,正如@Arg0n所说,更简单的解决方案似乎是将
包含在模板本身中,或者如果需要以某种方式对其进行参数化,则将其作为自己的指令。工作得很好!谢谢!
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)}
})
<ul>
<li ng-repeat="o in array"><div id="name">{{ o.name }}</div>
<!-- added compile-template -->
<div id="remove" ng-bind-html="o.remove" compile-template></div>
</li>
</ul>
.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() {
return (parsed(scope) || '').toString();
}
// Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); // The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});