【问题标题】:Migration to AngularJS 1.2 breaks sortable-wrapper directive迁移到 AngularJS 1.2 会破坏 sortable-wrapper 指令
【发布时间】:2013-11-19 13:02:32
【问题描述】:

我有一个 sortable-wrapper 指令,它允许在列表中移动项目以及从一个列表移动到另一个。

使用数组容器:

$scope.container = [
  [{id: '1.1'}, {id: '1.2'}, {id: '1.3'}],
  [{id: '2.1'}, {id: '2.2'}, {id: '2.3'}]
]

我使用这样的指令:

<div ng-repeat="array in container">
  <ul sortable>
    <li ng-repeat="item in array">{{ item.id }}</li>
  </ul> 
</div>

当一个项目被放入列表时,我必须更新项目后端并将后端返回的移动项目插入到正确的数组/索引中:

$scope.move = function (from, fromIndex, to, toIndex) {
  $http.post(url, data).success(function(movedItem) {
    from.splice(fromIndex, 1)[0];
    to.splice(toIndex, 0, movedItem);
  });
} 

此指令在 1.2.0-rc.2 版本之前运行良好,因为 1.2.0-rc.3 在移动项目时出现此错误:

TypeError: Cannot call method 'insertBefore' of null
    at http://code.angularjs.org/1.2.1/angular.js:3857:22
    at forEach (http://code.angularjs.org/1.2.1/angular.js:303:18)
    at Object.enter (http://code.angularjs.org/1.2.1/angular.js:3856:9)
    at http://code.angularjs.org/1.2.1/angular.js:18828:26
    at publicLinkFn (http://code.angularjs.org/1.2.1/angular.js:5443:29)
    at boundTranscludeFn (http://code.angularjs.org/1.2.1/angular.js:5555:21)
    at controllersBoundTransclude (http://code.angularjs.org/1.2.1/angular.js:6145:18)
    at ngRepeatAction (http://code.angularjs.org/1.2.1/angular.js:18826:15)
    at Object.$watchCollectionAction [as fn] (http://code.angularjs.org/1.2.1/angular.js:11347:11)
    at Scope.$digest (http://code.angularjs.org/1.2.1/angular.js:11443:27) 

这是一个重现错误的 plunker:http://plnkr.co/edit/bAD8z2KdW34a7hkhdyiu?p=preview

有什么想法吗?

【问题讨论】:

    标签: javascript jquery-ui angularjs jquery-ui-sortable


    【解决方案1】:

    使用这个:

    <li ng-repeat="item in array track by item.id">{{ item.id }}</li>
    

    为什么?

    我认为一旦它们的位置发生变化,您正在重新创建项目 (getNewItemFromBackend(item))。因为ngRepeat 是通过对象相等来跟踪它们,所以一旦对象离开列表,Angular 就找不到它来插入 DOM 元素。我对这个解释不是 100% 满意,但大致就是这样。

    【讨论】:

    • 使用此解决方案,在列表内移动项目时不再中断,但在列表之间移动项目时仍会中断:plnkr.co/edit/fXd2poFJjIPGccgOtk9m?p=preview
    • 这是因为 jQueryUI 和 Angular ngRepeat 都在更改 DOM,没有协调。我不知道有什么方法可以解决这个问题。
    【解决方案2】:

    最后,我将实现更改为使用 angular-ui ui-sortable 模块。 The angular 1.2 branch 考虑了 ng-repeat 指令 1.2 版本的变化。请参阅pull request

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2013-08-21
      • 2015-07-05
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多