2014-03-19 13 views
1

以下代碼需要在2個不同的控制器中(目前,稍後可能會有更多的控制器)。代碼解決了我在ng-grid中發現的一個問題,並允許延遲選擇一行(一旦數據被加載)。你在哪裏把這種控制器代碼放在一個角度應用程序中?

// Watch for the ngGridEventData signal and select indexToSelect from the grid in question. 
    // eventCount parameter is a hack to hide a bug where we get ngGridEventData spam that will cause the grid to deselect the row we just selected 
    function selectOnGridReady(gridOptions, indexToSelect, eventCount) { 
     // Capture the grid id for the grid we want, and only react to that grid being updated. 
     var ngGridId = gridOptions.ngGrid.gridId; 
     var unWatchEvent = $scope.$on('ngGridEventData', function(evt, gridId) { 
      if(ngGridId === gridId) { 
       //gridEvents.push({evt: evt, gridId:gridId}); 
       var grid = gridOptions.ngGrid; 

       gridOptions.selectItem(indexToSelect, true); 
       grid.$viewport.scrollTop(grid.rowMap[0] * grid.config.rowHeight); 

       if($scope[gridOptions.data] && $scope[gridOptions.data].length) { 
        eventCount -= 1; 
        if(eventCount <= 0) { 
         unWatchEvent(); // Our selection has been made, we no longer need to watch this grid 
        } 
       } 
      } 
     }); 
    } 

我現在的問題是我在哪裏放這個公共代碼?這顯然是UI代碼,所以它似乎不屬於服務,但沒有經典的繼承方案(我已經能夠發現),這將允許我把它放在一個「基類」

理想情況下,這將是ng-grid的一部分,不會涉及這樣一個討厭的黑客攻擊,但是ng-grid 2.0對特徵是封閉的,ng-grid 3.0是誰知道未來有多遠。

另一個摺痕是$ scope,我想我必須注入這個代碼,如果我從當前控制器中取出它。

這是否真的屬於服務?

+0

你可以嘗試使用一個mixin。 http://digital-drive.com/?p=188 – ivarni

回答

1

我可能會把它放在一個服務中,並將$ scope傳入它,但是你有其他的選擇。你可能想看看這個演講,因爲它涵蓋了組織代碼不同的方式:https://docs.google.com/presentation/d/1OgABsN24ZWN6Ugng-O8SjF7t0e3liQ9UN7hKdrCr0K8/present?pli=1&ueb=true#slide=id.p

混入

你可以把它放在自己的對象,並將其混入使用angular.extend任何控制器();

var ngGridUtils = { 
    selectOnGridReady: function(gridOptions, indexToSelect, eventCount) { 
     ... 
    } 
}; 

var myCtrl = function() {...}; 
angular.extend(myCtrl, ngGridUtils); 

繼承

如果使用「控制器」語法您的控制器,然後就可以像對待類,只是使用JavaScript繼承。

var BaseCtrl = function() { 
    ... 
} 

BaseCtrl.prototype.selectOnGridReady = function(gridOptions, indexToSelect, eventCount) { 
    ... 
}; 

var MyCtrl = function() { 
    BaseCtrl.call(this); 
}; 

MyCtrl.prototype = Object.create(BaseCtrl.prototype); 

HTML:

<div ng-controller="MyCtrl as ctrl"></div> 
+0

3種查看方式。非常感謝你。如果您感到面臨挑戰,我還有其他未解答的問題:-) – boatcoder

相關問題