我有一些带有一些通用代码的 Controller ,特别是一个与几个 Controller 相同的$scope.$watch。我如何才能将此代码放在单独的文件中,并将通用代码导入需要$watch的各种 Controller 中?

最佳答案

可以通过传入 Controller 的作用域来使用服务:

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);
}]);

这样,您可以使用单个 Controller 的作用域,但可以在服务中使用通用方法。如果要从实际添加到 Controller 作用域的服务中获得通用功能,也可以在 Controller 内使用angular.extend($scope, AService)

这是一个有效的 fiddle :http://jsfiddle.net/rhcjdb7L/

当然,这很酷,但是您确定您不想使用$rootscope.$broadcast()吗?这写得很好:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

关于AngularJS Controller : Move common code to separate file,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25936897/

10-12 13:03