ngRepeat不断重新创建

时间:2015-12-02 10:05:39

标签: javascript angularjs

我创建了一个模拟我的问题的fiddle。我正在使用ng-repeat来创建一些节点。但是这些节点将由另一个库(Openlayers)使用,它们将这些节点“移动”(appendChild)到DOM中的另一个位置。

因此,正在为这些节点而战。有没有办法告诉ngRepeat停止重新排序,重新创建(不确定最佳术语)?

http://jsfiddle.net/jonataswalker/dbxmbxu9/

标记

<button ng-click="create()">New Record</button>
<div data-label="Created here">
  <div 
      id="hint-{{$index}}" 
      class="hint--always hint--right" 
      data-hint="{{row.desc}}"
      ng-repeat="row in rows track by row.id"
      on-render>{{row.desc}}
  </div>    
</div>
<div id="wrap" data-label="I'd like all to be here"></div>

JS

app.controller('ctrl', ['$scope', function($scope) {
  $scope.rows = [];
  $scope.count = 0;
  var wrap = document.getElementById('wrap');

  $scope.create = function(){
    var c = $scope.count++;
    $scope.rows.push({
      id: c,
      desc: 'dummy-desc-' + c
    });
  };

  $scope.move = function(div){
    wrap.appendChild(div);
  };
}]);
app.directive('onRender', ['$timeout', function ($timeout) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      if (scope.$last === true) {
        $timeout(function(){
            scope.move(element[0]);
        });
      }
    }
  };
}]);

1 个答案:

答案 0 :(得分:1)

最后,我不得不放弃使用ng-repeat。感谢所有评论。

我找到的解决方案是使用$compile服务并让DOM操作自由。

http://jsfiddle.net/jonataswalker/y4j679jp/

app.controller('ctrl', ['$scope', function($scope) {
  $scope.rows = [];
  $scope.count = 0;
  var wrap = document.getElementById('wrap');

  $scope.move = function(div){
    wrap.appendChild(div);
  };
}]);
app.directive('button', ['$compile', function($compile){
  return {
    restrict: 'A',
    link: function(scope){
      var div = document.getElementById('c1');

      scope.create = function(){
        var c = scope.count++;
        var row = { id: 'hint-' + c, desc: 'any desc #' + c };
        var index = scope.rows.push(row) - 1;

        var html = [
          '<div id="'+row.id+'"',
          'class="hint--always hint--right"',
          'data-hint="{{rows['+index+'].desc}}"',
          'data-index="'+index+'"',
          'on-render>{{rows['+index+'].desc}}</div>'
        ].join(' ');

        angular.element(div).append($compile(html)(scope));
      };
    }
  };
}]);
app.directive('onRender', ['$timeout', function ($timeout) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      $timeout(function(){
        scope.move(element[0]);
      }, 2000).then(function(){
        $timeout(function(){
          scope.rows[attr.index].desc = 'changed .... ' + attr.index;
        }, 2000);
      });
    }
  };
}]);