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

我有一些带有一些通用代码的控制器,特别是$scope.$watch对于几个控制器是相同的.如何将此代码放在单独的文件中并导入需要此$watch的各种控制器中的公共代码
您可以通过传入控制器的范围来使用服务:
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',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/

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...