2017-01-16 51 views
1

我是AngularJS中的新成員,我正在做一個AngularJS應用程序的重構,並且我注意到有一個控制器文件包含許多操作和設置作用域變量的函數。AngularJS - 在多個文件中拆分控制器函數

下面的例子:

test.controller('testCtrl', function testCtrl($scope) { 

    $scope.init_filters = function() { 
     $scope.filter_1 = []; 
     $scope.filter_2 = []; 
     $scope.filter_3 = []; 
     $scope.filter_4 = []; 
     $scope.filter_5 = []; 
    }; 

    $scope.showChanges = function() { 
     if ($scope.item_list.length > 0) { 
      $scope.messages = []; 
      for (var i = 0; i < $scope.item_list.length; i++) { 
       $scope.messages.push($scope.item_list[i].message); 
      } 
      $scope.another_function(); 
     }else{ 
      // other stuff 
     } 
    }; 

    //other functions like these 

} 

所以,我想在多個JS文件分割這些功能。我搜索了這個問題,並發現在很多情況下使用了一項服務。但我認爲這不是我的情況,因爲我需要直接處理控制器的範圍。
我的意思是,我不想要一個分離的函數,作爲參數的一些範圍變量並返回變量。

那麼,做這種事情的最佳做法是什麼?可能嗎?

+0

如果你想遵循模塊化的方法。咖啡劇本與咕嚕聲允許做到這一點。請看看這個包'https:// github.com/gruntjs/grunt-contrib-coffee' –

回答

1

如果要使用多個文件,請將該範圍傳遞給另一個方法,然後再定義該方法的其餘方法,將該定義分割爲多個文件。

文件1

app.controller('CtrlOne', function($scope){ 
app.expandControllerCtrlOne($scope); 

}); 

文件2

app.expandControllerCtrlOne = function($scope) 
{ 

} 

入住這video

0

你可以通過$scope作爲參數傳遞給外部函數。 因爲您只是使用objectreference,所以您在外部函數中所做的所有更改都是從控制器的$scope對象上進行的。

test.controller('testCtrl', function testCtrl($scope) 
{ 
    showChanges($scope); 
}); 


... 

function showChanges(scope) 
{ 
    scope.param1 = "Hello World"; 
} 
1

正如你所說,你發現控制器的代碼很大,所以角js有多種方法可以實現代碼分離。

我會建議你用下面的方法去:

  1. 使用服務添加它,你在其他地方需要,以及那些代碼,你知道,這個代碼不需要範圍對象..

  2. 使用工廠添加一些實用類型的功能。不需要再範圍對象邏輯的集合...

  3. 由於控制器代碼太大,我想的一樣查看/ UI也正在按照寫道... 因此,對於這個你可以去與爲部分創建指令 .. 哪裏 - 你認爲這個和平觀點部分可以是單獨的和獨立的邏輯功能,你可以進入指令。 有三種方式與範圍創建指令:

A.共享範圍B.隔離範圍C:共享和隔離範圍

以這種方式,您至少可以讓您的控制器代碼可讀並且看起來是模塊化的。

咱們說::

module.controller('longRunController', function() { 


    @TYPE 1 code 
    // some code which fetch dat from API 
    // some code which save variable and objects which can used in another controller or directives 
    // some code which need to passed to other controller even after route changes 


    @TYPE 2 
    // some code which is only related this controller but has some bussiness logic 
    // some code which is a kind of utility functino 

    @TYPE 3 
    // all $scope related variable $watch, $scope and related variables 
    // some code of perticular section of which VIEW which handle by this controller 

}); 

考慮上述圖案控制器代碼有:

  1. 所以1型碼可以被移動到服務
  2. 2型碼可以移動到工廠
  3. 類型3代碼可以移至指令
+0

感謝您的回答!你能否爲我提供一個3點的例子? – Giordano