2014-09-19 69 views
8

我有一些控制器與一些公用代碼,具體來說$scope.$watch是幾個控制器相同。我怎樣才能把這個代碼放在一個單獨的文件中,並在需要這個$watch的各種控制器中導入公共代碼?AngularJS控制器:將公共代碼移動到單獨的文件

+0

可以爲此服務嗎? – worldask 2014-09-19 15:45:49

+0

我很確定服務範圍是不可能的...... – EricC 2014-09-19 15:49:14

+0

@EricC $ scope只是一個服務函數的參數。 – cgTag 2014-09-19 16:20:14

回答

7

可以通過傳遞您的控制器的範圍內使用服務:

angular.module('app').service("CommonFunctions", ['SomeService', function(SomeService) { 
    var commonFunctions = {}; 
    commonFunctions.init = function(scope){ 
     scope.$watch(function(){},function(){}) 
    }; 
    return commonFunctions; 
}]); 

angular.module('app').controller('Ctrl1', 
['$scope','CommonFunctions',function($scope,CommonFunctions) { 
    CommonFunctions.init($scope); 
}]); 

angular.module('app').controller('Ctrl2', 
['$scope','CommonFunctions',function($scope,CommonFunctions) { 
    CommonFunctions.init($scope); 
}]); 

這種方式,你正在使用的個人控制的範圍,但使用服務中的常用方法。如果您想從實際添加到控制器作用域的服務獲得常用功能,則還可以在控制器內使用angular.extend($scope, AService)

這裏的工作小提琴http://jsfiddle.net/rhcjdb7L/

肯定這是非常冷靜和所有,但你確定你不想使用$rootscope.$broadcast()?這是寫得很好:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

+0

我沒有看到擴展$範圍的要點。你已經有一個服務。只需調用'CommonFunctions.init($ scope)' – cgTag 2014-09-19 16:21:49

+0

你是對的,'extend()'在這種情況下是矯枉過正的,因爲你不需要$ scope中的那個函數。我修改了我的答案。 – 2014-09-19 16:35:04

+0

謝謝你們:) – EricC 2014-09-19 17:47:10

相關問題