在ngclick上动态生成指令内容

时间:2016-06-27 15:43:54

标签: angularjs

我有一张桌子。因为我已经宣布了我的自定义指令

<table ng-show="dataset.length" ng-table="tableParams" class="table">
    <thead>
        <tr>
            <th></th>   
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="server in $data" ng-class-odd="'odd-row'" ng-class-even="'even-row'">
            <td width="30" class="text-center">
                <i class="ion-plus-round **toggle-icon**" group-row></i>
            </td>
        </tr>
    </tbody>
</table> 

点击切换图标

我需要在下一行再生成一个tr数据。

自定义指令

app.directive('groupRow', function(){

    return {
      restrict: 'EA',
         transclude: true,
        controller: 'groupRowDirCtrl',
        templateUrl: 'views/directives/templates/group-row.html',
        link: function( scope, element, attrs, groupRowDirCtrl ) {
            element.bind('click', function() {
                $compile(el)(scope);
                element.parent().parent().after(el);
            });
        }
    };
})
.controller('scrollableTableviewDirCtrl',
    function($scope) {
});

数据必须从html页面获取并附加到下一行。

怎么做?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,点击功能就在指令中。

所以,我会为正在重复的 $ data 数组添加一项服务,并在点击时使用该服务向该数组添加另一项。

喜欢这样

&#13;
&#13;
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, dataService) {
  dataService.setData([1, 2, 3]);

  $scope.data = dataService.getData();
});

app.directive('dir', function(dataService) {
  return {
    restrict: 'E',
    replace: true,
    template: '<tr><td ng-click="addMore()">One More</td></tr>',
    link: function($scope, elem, attrs) {
      $scope.addMore = function() {
        dataService.addRow();
      }
    }
  }
});


app.service('dataService', function() {
  var _data = [];
  var _service = {};
  var _cb;

  _service.getData = function() {
    return _data;
  }


  _service.setData = function(data) {
    _data = data;
  }

  _service.onUpdate = function(cb) {
    _cb = cb;
  }

  _service.addRow = function( /* attibutes here */ ) {
    _data.push({});
    if (angular.isFunction(_cb)) _cb();
  }

  return _service;
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <table>
      <tbody>
        <dir ng-repeat="d in data"></dir>
      </tbody>

    </table>
  </div>
</div>
&#13;
&#13;
&#13;