2015-11-13 13 views
0

我有一個網格生成與打包,我需要根據一些條件向網格中的每個元素添加兩個類。我使用ng-if來添加它們,它工作正常,但是每當我這樣做時,網格都不會加載。我相信它與子範圍有關 - 如果正在創建,但我不知道這是什麼工作。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 謝謝!

+0

使用'ng-show'。 'ng-show'不會像ng-if一樣創建子作用域 – harishr

+0

ng-show的作用是它以不同的方式打破了網格。任何關於應該怎麼做才能獲得ng的想法 - 如果按照它應該做的那樣工作? – keyserfaty

回答

0

問題是,你不應該依賴某個標籤是否爲你創建一個範圍。

不要使用activeUser它不合格。

相反,你需要把它放在某個對象,像

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

然後,當你引用它,你可以使用

{{ something.activeUser }} 

ng-if="!something.activeUser" 

無任何危險的任何人打破你的變量。

+0

你能寫一個如何實現這個例子嗎?非常感謝您的回答。 – keyserfaty

+0

我的回答應該是自我解釋。 – ergonaut

+0

我改變了這個:'$ scope.smt.activeUser = true;'然後:'ng-if =「{{smt.activeUser}}」可拖動的可變形「但結果仍然相同 – keyserfaty