gpt4 book ai didi

AngularJS 拦截并扩展 Controller $scope

转载 作者:行者123 更新时间:2023-12-04 02:53:29 25 4
gpt4 key购买 nike

我在我的应用程序中定义了许多可重用的功能,每个 Controller 都使用 $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() { ... };
}]);

然后后来:
var HomeCtrl = function($scope) {
$scope.method1();
};

这可能吗?或者我是否需要创建一个共享服务,然后将 $scope 扩展到每个 Controller 的第一行?

最佳答案

而不是 .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
}]);

注意 我只用过 module.controller因为喜欢, var HomeCtrl = function($scope) {会有同样的效果。

关于AngularJS 拦截并扩展 Controller $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11956667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com