【问题标题】:Push trustAsHtml with directive to ng-repeat将带有指令的 trustAsHtml 推送到 ng-repeat
【发布时间】: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)}
    })

这是一个例子http://plnkr.co/edit/0WFmvT?p=preview

【问题讨论】:

  • remove 中是否会有不同的 HTML,或者为什么要将其添加为 string 而不是模板?
  • 是的,正如@Arg0n 所说,更简单的解决方案似乎是将&lt;button&gt; 包含在模板本身中,或者如果需要以某种方式对其进行参数化,则使其成为自己的指令。

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

查看此链接,Using ng-bind-html and $sce.trustAsHtml create a string with ng-model binding 已添加编译模板指令,更新 plnkr:http://plnkr.co/edit/veKAGjXoJ7DKeC233wbj?p=preview

在 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>

在 JS 中:

.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
            });
        }
    }
});

【讨论】:

  • 工作就像一个魅力!谢谢!
猜你喜欢
  • 2023-03-05
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多