javascript - AngularJs jQuery : Add HTML dynamically

标签 javascript jquery angularjs

我的列和行已使用 jQuery 正确添加,但是,当单击按钮时,它不会在 Controller 中调用我的警报函数“hello()”!

这是我针对该问题的 jsfiddle 链接:https://jsfiddle.net/said_kossouri/cw3f119h/

HTML:

<div ng-app ng-controller="LoginController">
 <table  border="1" id="mtable" class="table table-striped">
      <thead><tr>
          <td>Item</td>
          <td><button id="deleteColl">Ok</button></td>

        </tr></thead>

      <tbody><tr>
        <td>Some Item</td>
        <td><input type="text"/></td>

      </tr></tbody>

  </table><br/>
  <button ng-click="addRow()" id="irow">+ Row</button>
  <button ng-click="addCol()" id="icol">+ Column</button>

JS:

function LoginController($scope) {
    $scope.addRow = function () {
    $('#mtable tbody').append($("#mtable tbody tr:last").clone());
    $('#mtable tbody tr:last :checkbox').attr('checked',false);
    $('#mtable tbody tr:last td:first').html($('#row').val());
  }

  $scope.addCol = function () {
    $('#mtable tr').append($("<td>"));
    $('#mtable thead tr>td:last').html('<button ng-click="hello()">Hello!</button>');
    $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))});   
  }  

  $scope.hello = function () {
    alert("HELLO");
  }

}

最佳答案

问题在于不同的上下文、进程/执行时间。最好的方法是只使用 jQuery 或 Angularjs。

仅使用 Angularjs:

  • 用一个对象来表示表格(矩阵)
  • 添加行函数将向表对象追加一行
  • 添加 col 函数将在表对象的行上附加一列

初始化表对象:

$scope.table = [];

添加行函数:

$scope.addRow = function () {
    $scope.table.push([]);
}

添加col函数

$scope.addCol = function (row) {
    row.push('col value');
}

用 Angularjs 渲染表格:

<!-- rows -->
<tr ng-repeat="row in table">
    <!-- cols -->
    <td ng-repeat="col in row">
        {{ col }}
    </td>

    <td>
        <button type="button" ng-click="addCol(row)">New col</button>
    </td>
</tr>

<button type="button" ng-click="addRow()">New row</button>

由于 addCol 函数需要列目标来添加新项目,因此操作按钮需要在行内。

关于javascript - AngularJs jQuery : Add HTML dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41902747/

相关文章:

javascript - CSS 按钮图像 :hover

javascript - 附加到 div 时 gif 图像的相对路径会中断吗?

javascript - 选择列表未填充 (jQuery Ajax)

javascript - jQuery slideToggle 嵌套 div

javascript - 从 UICalendar 中选择一天

javascript - 复制渲染表的功能随机停止工作,页面刷新修复了这个问题

javascript - 使用 NodeJS 和鹰嘴 bean 泥替换 PDF 中的文本时出错

javascript - 鼠标悬停在图片上

angularjs - 如何使用来自同一来源的不同值设置默认选定的下拉列表

javascript - Angularjs 使用 ng-if 进行选择性 ng-repeat