Reputation: 926
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()
}]);
Upvotes: 4
Views: 1775
Reputation: 455
Your best bet might be to use Services or Factories, and then inject these as dependencies when needed throughout your application.
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>
Upvotes: 2
Reputation: 16577
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:
Upvotes: 1