ng-if在创建子范围时中断网格

时间:2015-11-13 14:59:21

标签: javascript angularjs

我有一个带有packery的网格构建,我需要根据某些条件为网格中的每个元素添加两个类。我使用ng-if添加它们并且工作正常,但每当我这样做时,网格都不会加载。我相信它与孩子的范围有关 - 如果正在创造,但我不知道最新的工作。

HTML:       

    <div class="columnWidth rowHeight">

      <div class="gutter"></div>
      <div ng-repeat="shot in shots track by shot.id">

        <img
          id="{{ shot.id }}"
          ng-src="{{ shot.images.normal }}"
          class="itemSelector" ng-class="itemClass(shot.id)"
          ng-if="activeUser" draggable starable>

        <img
          id="{{ shot.id }}"
          ng-src="{{ shot.images.normal }}"
          class="itemSelector" ng-class="itemClass(shot.id)"
          ng-if="!activeUser">

      </div>

    </div>

  </div>

控制器:

$scope.$apply(function () {
  $scope.activeUser = true;
});

指令:

angular.module('board.directives', [])

  .directive('packeryGrid', ['$rootScope', '$window', function ($rootScope, $window) {
    return {
      restrict: 'A',

      link: function (scope, element, attrs) {

        angular.element(document).ready(function () {

          scope.$watch('board', function () {
            $rootScope.packery = new Packery(element[0], {
              itemSelector: '.itemSelector',
              columnWidth: '.columnWidth',
              rowHeight: '.rowHeight',
              gutter: '.gutter'
            });

          });

        });
      }
    };
  }])

  .directive('draggable', ['$rootScope', 'api', function ($rootScope, api) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var draggable = new Draggabilly(element[0]);
        $rootScope.packery.bindDraggabillyEvents(draggable);
        $rootScope.packery.layout();
      }
    };
  }])

  .directive('starable', ['$rootScope', 'api', function ($rootScope, api) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        element.bind('dblclick', function () {
          element.toggleClass('itemSelectorBig');
          api.board().one('starred-shot', attrs.id).put();
          $rootScope.packery.layout();
        });

      }
    }
  }]);

完整代码:http://plnkr.co/edit/cx9oJtNnRusKZrHrMipS?p=info 谢谢!

1 个答案:

答案 0 :(得分:0)

问题在于,您不应该依赖某个标签是否为您创建范围。

不要使用activeUser它不合格。

相反,你需要把它放在某个对象中,比如

$scope.something = {};
$scope.something.activeUser = ....

然后当你引用它时,你可以使用

{{ something.activeUser }} 

ng-if="!something.activeUser"

没有任何人破坏你的变量的危险。