AngularJS拦截和扩展控制器$范围 [英] AngularJS Intercept and extend controller $scope

查看:96
本文介绍了AngularJS拦截和扩展控制器$范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多的,我在每个控制器的$范围变量使用我的应用程序定义了可重复使用的功能。而不是我不必每次都创建一个共享的服务,有没有办法延长$范围的变量,这样我可以有我的扩展code随处可见?

There is a lot of reusable functionality that I have defined in my application that EVERY controller uses with the $scope variable. Instead of me having to create a shared service each time, is there a way to extend the $scope variable so that I can have my extended code available everywhere?

是这样的:

//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() { ... };
}]);

再后来就:

var HomeCtrl = function($scope) {
  $scope.method1();
};

这可能吗?还是我需要创建一个共享服务,然后有$范围从延长每个控制器的第一行?

Is this possible? Or do I need to create a shared service and then have the $scope extend from that for the first line of each controller?

推荐答案

而不是的.config 尝试 .RUN ,这将不正是你想要的。

Instead of .config try .run, this will do exactly what you want.

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

注意我只用 module.controller ,因为我喜欢它, VAR HomeCtrl =功能($范围内) {将有同样的效果。

NOTE I have only used module.controller because I like it, var HomeCtrl = function($scope) { will have the same effect.

这篇关于AngularJS拦截和扩展控制器$范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆