javascript angularJS 中的全局函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28541179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:08:16  来源:igfitidea点击:

Global Functions in angularJS

javascriptangularjsangularjs-scopeangular-ui

提问by Adnan Ali

I am new to angularJS. So need help on how to add global functions in angular project? File loading my angular app is using showScrollAndGo function which should be work as global method but it is not working. Code of app.js is:

我是 angularJS 的新手。那么需要关于如何在 angular 项目中添加全局函数的帮助吗?加载我的 angular 应用程序的文件正在使用 showScrollAndGo 函数,该函数应该作为全局方法工作,但它不起作用。app.js 的代码是:

'use strict'; define(
[
    'angular',
    'jQuery',
    'angular-route',
    'angular-resource',
    'angular-ui-bootstrap',
    'highcharts',
    'highcharts-theme',
    'highcharts-ng',
    'controllers/index',
    'directives/index',
    'filters/index',
    'services/index',
    'angular-token-auth',
    'angular-local-storage',
    'jquery.slimscroll',
    'jquery-icheck'
],
function(angular, $) {
    'use strict';
    return angular.module('radian', ['ngRoute', 'ngResource', 'ui.bootstrap', 'app.services', 'app.controllers', 'app.directives','app.filters', 'highcharts-ng', 'ng-token-auth', 'ngStorage'])
        .constant('globals', {
            API_URL: 'http://localhost:3000/api',
            AUTH_URL: 'http://radiancor-env.elasticbeanstalk.com',
            TEMPLATE_URL: 'app/views'
        })
        .constant('pagination', {
            items_per_page: 10,
            max_size: 5,
            direction_links: true,
            boundary_links: true,
            current_page: 1,
            total_items: 0
        })
        .config(['$routeProvider', 'globals', routeConfiguration])
        .config(['$httpProvider', httpConfiguration])
        .config(['$authProvider', 'globals', authProvider])
        .config(['$rootScopeProvider', root_functions])
        .config(['paginationConfig', paginationConfiguration]);

    function authProvider($authProvider, globals) {
        $authProvider.configure({
            apiUrl: globals.AUTH_URL
        });
    }

    function paginationConfiguration(paginationConfig) {
        paginationConfig.firstText = '<<';
        paginationConfig.lastText = '>>';
        paginationConfig.nextText = '>';
        paginationConfig.previousText = '<';
    }

    function routeConfiguration($routeProvider, globals) {
        $routeProvider
            .when('/', {
                templateUrl: globals.TEMPLATE_URL+'/misc/login.html',
                controller: 'LoginController',
                controllerAs: 'login'
            })
            .when('/dashboard', {
                templateUrl: globals.TEMPLATE_URL+'/misc/dashboard.html',
                controller: 'DashboardController',
                controllerAs: 'dashboard'
            })
            .when('/entity/:entity/:action', {
                templateUrl: function(rp) {
                    return globals.TEMPLATE_URL+'/'+rp.entity+'/'+rp.action+'.html';
                }
            })
            .when('/entity/:entity/:action/:id', {
                templateUrl: function(rp) {
                    return globals.TEMPLATE_URL+'/'+rp.entity+'/'+rp.action+'.html';
                }
            })
            .otherwise({
                redirectTo: '/'
            });
    }

    function httpConfiguration($httpProvider) {
        $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
        $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.interceptors.push('interceptService');

    }

    function root_functions($rootScope) {
        $rootScope.showScrollAndGo = function(path) {
            alert("I'm global foo!");
        };
    }

});

I need to access showScrollAndGoin different views. So trying to make it global. Any idea where I am doing wrong?

我需要在不同的视图中访问showScrollAndGo。所以试图让它成为全球性的。知道我哪里做错了吗?

I am using it in view like this:

我在这样的视图中使用它:

<a href="#/entity/clients/list" data-ng-click="showScrollAndGo('aaa');"><i class="fa fa-circle mrm mlm"></i>Manage Clients</a>

采纳答案by Rebornix

Referring to Angular's document

参考 Angular 的文档

angular.module('myModule', []).
config(function(injectables) { // provider-injector
  // This is an example of config block.
  // You can have as many of these as you want.
  // You can only inject Providers (not instances)
  // into config blocks.
}).
run(function(injectables) { // instance-injector
  // This is an example of a run block.
  // You can have as many of these as you want.
  // You can only inject instances (not Providers)
  // into run blocks
});

You need config the rootScope at run phase like

您需要在运行阶段配置 rootScope,例如

app.run(function($rootScope) {
  $rootScope.showScrollAndGo = function(path) {
        alert("I'm global foo!");
    };
});

回答by M.K

You can try adding a factory, and refer that factory in all the controllers where u need it.

您可以尝试添加一个工厂,并在您需要的所有控制器中引用该工厂。

Sample:

样本:

In app.js add a factory:

在 app.js 中添加一个工厂:

app.factory('notificationFactory', function (toaster) {
    //.............
});

In any Controller file you can refer this factory by name and use it like below,

在任何控制器文件中,您都可以按名称引用此工厂并使用它,如下所示,

app.controller('sampleController', ['$scope','notificationFactory',
    function ($scope, notificationFactory) {
    }
]);