简体   繁体   中英

Share functions between controllers AngularJS

I'm assuming this is quite straightforward, but how can I have global functions that I can access in my controllers by storing the function in the '.run' phase?

Quite simply, a button is clicked in the DOM that triggers the global function that is called in the appropriate controller..

I've tried various methods and would like a really simple approach to this that helps to minimise the amount of code I've currently got. See below:

**HTML**

<input data-ng-click="clearSignInError()" data-ng-model="email" 
type="email"
id="inputEmail" class="form-control" placeholder="Email address"   
required>

**JS**

app.run(['$rootScope', '$state', function($rootScope, $state) {

    $rootScopecope.clearSignInError = function () {
        $rootScope.loginError = null;
        $rootScope.loginSuccess = null;
    };

}]);

app.controller('loginCtrl', ['$scope', 'Auth', '$state', '$rootScope'
    function($scope, Auth, $state, $rootScope) {

    $rootScope.clearSignInError()

}]);

Your best bet might be to use Services or Factories, and then inject these as dependencies when needed throughout your application.

Angular Services

Angular Factories

Edit: Added an example service in this plunkr

https://plnkr.co/edit/zqWS9gkTsm2OF1FTb24Z?p=preview

app.service('AuthService', function() {
    this.loginSuccess = function() {
        // do stuff when login is successful
    }

    this.loginError = function() {
        // handle login errors here
    }

    this.clearLoginError = function() {
        console.log("Clear Login Error");
        alert("Clear Login Error");
    }
});

// modified your controller
app.controller('loginCtrl', ['$scope', 'Auth', 'AuthService', '$state', '$rootScope', function($scope, Auth, AuthService, $state, $rootScope) {

    $scope.clearSignInError = AuthService.clearLoginError;

}]);

**HTML**
<input data-ng-click="clearSignInError()" data-ng-model="email"
type="email" id="inputEmail" class="form-control" placeholder="Email address" required>

You can make use of a factory instead of hooking up with rootScope. In this way, you can include your factory as a dependency in any controller you want. Here's a video demonstration which might help you to get started:

Factories In AngularJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM