javascript - 表行的 AngularJS 指令中的动态 `template`

标签 javascript html angularjs angularjs-directive

我可以动态加载 AngularJS 指令吗 templateUrl什么时候在 table 上工作

我有以下 HTML,重复 trfw-rule指令:

<tbody>
  <tr ng-repeat="rule in data | orderBy:predicate:reverse" fw-rule="rule">
  </tr>
</tbody>

我想要那个 tr 的内容不同,取决于“编辑”变量的状态。

下面是我的一个部分(另一个只是布局的变体):

<td><input type="checkbox"></td>
<td ng-click="isEditing=!isEditing">{{ fwRule.name }}<br><span class="rule-description">{{ fwRule.description }}</span></td>
<td>{{ fwRule.source }}</td>
<td>{{ fwRule.destination }}</td>
<td>{{ fwRule.protocol }}</td>
<td>{{ fwRule.schedule }}</td>
<td>{{ fwRule.action }}</td>
<td>{{ fwRule.reporting }}</td>

我在SO这里复习了以下两个问题,几乎给了我答案:

但是,他们都调用写指令的template使用 <div ng-include"getTemplateUrl()"></div> ,例如:

app.directive('fwRule', function () {
  return {
    restrict: 'A',
    scope: {
      fwRule: '='
    },
    controller: function ($scope) {
      $scope.getTemplateUrl = function () {
        // a check would be made here to return the appropriate partial
        return 'partials/RuleEditTableRow.html'
      }
    },
    link: function (scope, element, attrs) {
    },
    template: '<div ng-include="getTemplateUrl()"></div>'
  };
});

这在我的情况下不起作用,因为 div不是 tr 的有效子项(也不是 span ,我也试过)。因此,浏览器会在表格外呈现该内容。

有没有办法动态更新 template指令,不使用 ng-include , 以便它可以在表内运行?

最佳答案

您可以使用$compile 服务来编译正确的模板

app.directive('fwRule', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            fwRule: '='
        },
        controller: function ($scope) {},
        link: function ($scope, element, attrs) {
            var template = '<td>cell 1</td><td>cell 2</td>';

            angular.element(element).html(template);
            $compile(element.contents())($scope);
        }
    };
});

我想我可以在这个 fiddle 中使用您的代码:http://jsfiddle.net/ztv5gwwx/4/

关于javascript - 表行的 AngularJS 指令中的动态 `template`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212970/

相关文章:

javascript - JS自动滚动循环

javascript - 将 html 表单的多个输入值从一个输入字段传递给 JavaScript 事件函数

javascript - 如何通过标签 "selected"改变背景图片

javascript - 为什么 HTML5 checkValidity() 返回的结果与 JavaScript regexp.test() 不同?

Hotmail 中的 HTML 电子邮件通讯问题

angularjs - 根据状态有条件地设置 Angular 的 ng-class

javascript - 试图让 firebase.auth().currentUser 成为一个 promise

javascript - 为 Jquery UI 日期选择器指定冬季日期范围

javascript - 获取点击元素的索引

javascript - AngularJS 指令模糊事件未设置验证