2016-08-24 55 views
0

我有NG-重複內部指令。而且我在數組項目的變化順序中有切換功能。當我顯示範圍模型時,我看到那些項目改變了他們的順序,但UI沒有更新。嘗試範圍。$ apply()但它表示進程繁忙。AngularJs指令視圖不更新的NG-重複

.directive('example', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     template: ` 
       Checking model: {{model}} 

       <div ng-repeat="(key, row) in model"> 
         <div ng-hide="key == 0"> 
          <div class="icon-arrow-u" ng-hide="$first" ng-click="moveUp(key)"></div> 
          <div class="icon-delete" ng-click="removeCell(key)"></div> 
          <div class="icon-arrow-d" ng-hide="$last" ng-click="moveDown(key)"></div> 
         </div> 
        </div> 
       </div> 
     `, 
     scope: { 
      model: '=' 
     }, 
     link: function(scope, element) { 
      scope.moveItem = function (origin, destination) { 
       var temp = scope.model[destination]; 
       scope.model[destination] = scope.model[origin]; 
       scope.model[origin] = temp; 
      }; 

      scope.moveUp = function(index) { 
       scope.moveItem(index, index - 1); 
      } 

      scope.moveDown = function(index) { 
       scope.moveItem(index, index + 1); 
      } 
     } 
    } 
}) 

回答

2

沒有看到一個代碼小提琴,我猜想,其原因就在於在ng-repeat指令中。您應該添加一個track by表達式(請參閱AngularJS doc

例如,您可以編寫(key, row) in model track by key(key, row) in model track by row。無論哪種方式,它必須是每行都唯一的值。

+0

「通過鑰匙追蹤」工作。奇怪的原因,當我試圖「追蹤$索引」它沒有做任何改變。謝謝! – user256968

+0

這是因爲你正在遍歷一個對象。另外,「track by $ index」只有在元素索引不會改變時纔有效。 – Christoph

1

當使用directives時,範圍被隔離。您需要應用範圍才能看到更改。

每個函數添加以下代碼中的鏈接或當事件被調用。

內部鏈接功能用途:

 if (scope.$root.$$phase != '$apply' && 
      scope.$root.$$phase != '$digest') { 
      scope.$apply(); 

     } 

從主控制器

 if ($scope.$root.$$phase != '$apply' && 
      $scope.$root.$$phase != '$digest') { 
      $scope.$apply(); 

     } 

如果不工作,嘗試調用此對每個事件。

function apply(scope) { 
    if (!scope.$$phase && !scope.$root.$$phase) { 
    scope.$apply(); 
    console.log("Scope Apply Done !!"); 
    } 
    else { 
    console.log("Scheduling Apply after 200ms digest cycle already in progress"); 
    setTimeout(function() { 
     apply(scope) 
    }, 200); 
    } 
} 

希望這會有所幫助。

+0

你使用了那種確切的語法嗎?如果它說它很忙,那麼可能有助於在$ timeout中使用它作爲最後的手段。 –