AngularJS拦截并扩展控制器$ scope

mat*_*sko 10 angularjs

我在应用程序中定义了许多可重用的功能,每个控制器都使用$ scope变量.而不是每次都必须创建共享服务,有没有办法扩展$ scope变量,以便我可以在任何地方使用我的扩展代码?

就像是:

//I've tested this out and it doesn't work, but this is what I want to do.
angular.module('App',[]).config(['$scopeProvider',function($scope) {
  $scope.method1 = function() { ... };
  $scope.method2 = function() { ... };
}]);
Run Code Online (Sandbox Code Playgroud)

然后是:

var HomeCtrl = function($scope) {
  $scope.method1();
};
Run Code Online (Sandbox Code Playgroud)

这可能吗?或者我是否需要创建共享服务,然后让$ scope从每个控制器的第一行扩展?

Ren*_*des 23

而不是.config尝试.run,这将完全符合您的要求.

angular.module('App', []).run(['$rootScope', function($rootScope) {
  $rootScope.foo = function() {
     alert("WIN!");
  };
}]);

angular.module('App').controller('HomeCtr', ['$scope', function($scope) {
  $scope.foo(); #will call the alert
}]);
Run Code Online (Sandbox Code Playgroud)

注意我只使用module.controller因为我喜欢它,var HomeCtrl = function($scope) {会产生相同的效果.