Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

javascript - Creating common controller functions

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

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

How should I do it in AngularJS?

question from:https://stackoverflow.com/questions/11324202/creating-common-controller-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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. )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...