本文介绍了创建通用控制器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建某种可从我的所有控制器访问的工具包?

How do I create some sort of utils bundle that would be accessible from all my controllers?

我的主模块中有这个路由代码:

I have this route code in my main module:

'use strict';

angular.module('lpConnect', []).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/home', {template: 'views/home.html', controller: HomeCtrl}).
        when('/admin', {template: 'views/admin.html', controller: AdminCtrl}).
        when('/connect', {template: 'views/fb_connect.html', controller: MainAppCtrl}).
        otherwise({redirectTo: '/connect'});
}]);

我想要一个可以对 HomeCtrlAdminCtrlMainAppCtrl 通用的函数.

I want a function that can be common to HomeCtrl, AdminCtrl and MainAppCtrl.

我应该如何在 AngularJS 中做到这一点?

How should I do it in AngularJS?

推荐答案

在 angular 中定义公共代码的方式是通过 Services.

The way to define common code in angular is through Services.

您可以像这样定义一个新服务:

You would define a new service like so :

.factory('CommonCode', function ($window) {
        var root = {};
        root.show = function(msg){
            $window.alert(msg);
        };
        return root;
    });

在你的控制器中你会注入这个服务..像这样

In your controller you would inject this service..like so

function MainAppCtrl($scope,CommonCode)
{
     $scope.alerter = CommonCode;
     $scope.alerter.show("Hello World");
}

只需将 CommonCode 作为参数包含在您的控制器函数中.Angular 将负责为您注入它(阅读依赖注入..以了解这里发生的事情.)

Just include CommonCode as an argument to your controller function.. Angular will take care of injecting it for you ( Read on Dependancy Injection ..to understand what is happening here. )

这篇关于创建通用控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:05