AngularJS控制器:将公共代码移动到单独的文件

时间:2014-09-19 15:00:17

标签: angularjs

我有一些带有一些公共代码的控制器,特别是对于几个控制器来说相同的$scope.$watch。如何将此代码放在单独的文件中并将公共代码导入需要此$watch的各种控制器中?

1 个答案:

答案 0 :(得分:8)

可以通过传入您的控制器范围来使用服务:

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/

相关问题