创建自定义ng-repeat以避免在angularjs

时间:2017-04-18 18:11:04

标签: javascript angularjs angularjs-directive angularjs-watch

我正在使用ng-repeat的自定义指令来避免$watch。我试图修改指令,尽可能跳过$watchCollection()。但如果没有这个,我无法访问指令中的数据。

是否可以创建一个从dom获取模型值并在不创建$watch的情况下更新页面DOM的指令?

myRepeatDirective之后,我想要在没有$watch的情况下重新创建此指令。

我已经厌倦了对::使用一次约束(ng-repeat),但是它使用了分页。网格加载后不会更新。

提前致谢。

.directive('myRepeat', [ '$animate', function($animate) {

  var updateScope = function(scope, index, valueIdentifier, value, key, arrayLength) {
    scope[valueIdentifier] = value;
    scope.$index = index;
    scope.$first = (index === 0);
    scope.$last = (index === (arrayLength - 1));
    scope.$middle = !(scope.$first || scope.$last);
    scope.$odd = !(scope.$even = (index&1) === 0);
  };

  return {
    restrict: 'A',
    transclude: 'element',
    compile: function($element, $attrs) {

      var expression = $attrs.myRepeat;

      var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)?\s*$/);

      var valueIdentifier = match[1];
      var collection = match[2];

      return function($scope, $element, $attr, ctrl, $transclude) {

        $scope.$watchCollection(collection, function(collection) {
          var index, length,
            previousNode = $element[0],
            collectionLength,
            key, value;

            collectionLength = collection.length;

            for (index = 0; index < collectionLength; index++) {
              key = index;
              value = collection[key];

              $transclude(function(clone, scope) {
                $animate.enter(clone, null, angular.element(previousNode));
                previousNode = clone;
                updateScope(scope, index, valueIdentifier, value, key, collectionLength);
              });

            }
        });

      }
    }
  }

}]);

0 个答案:

没有答案