I have a few functions that do redirection on angularjs:
$scope.a= function()
{
$location.url('/a');
return;
}
$scope.b= function()
{
$location.url('/b');
return;
}
$scope.c = function()
{
$location.url('/c');
return;
}
$scope.d= function()
{
$location.url('/d');
return;
}
$scope.e= function()
{
$location.url('/e');
return;
}
$scope.f= function()
{
$location.url('/f');
return;
}
These have been declared inside one controller but I want every other js controller to have access to it. I want to avoid having to copy and paste these functions in every other controller. How do I achieve this?
angular routes:
var hot_keys = [
['. p','a','RedirectService.a()'],
['. o','b','RedirectService.b()'],
['. i','c','RedirectService.c()'],
['. f','d','RedirectService.d()'],
['. v','e','RedirectService.e()'],
['. a','f','RedirectService.f()']
];
.when('/a', {
templateUrl: 'templates/a',
controller: 'aController',
hotkeys: hot_keys
})
what this does is if user presses ". a" it should call the RedirectService.a();
Create a redirectService
and inject him the $location
.
He will do the redirecting.
Inject the redirectService
to the controllers who need it.
If you need them on your scope then you can:
1.Add them to the rootScope
.
2.Use controller inheritance(eg each controller who needs them will inherit a base contoller). Read here for more info.
Please make all the scope functions to rootScope functions. Please check the below code.
$rootScope.a= function()
{
$location.url('/a');
return;
}
$rootScope.b= function()
{
$location.url('/b');
return;
}
$rootScope.c = function()
{
$location.url('/c');
return;
}
$scope.d= function()
{
$location.url('/d');
return;
}
$rootScope.e= function()
{
$location.url('/e');
return;
}
$rootScope.f= function()
{
$location.url('/f');
return;
}
You can create a service ( https://docs.angularjs.org/guide/services ) which can contain these functions with $location injected into it.
And this service can be injected into the controllers where you need it.
Another solution would be to use ui-router ( https://github.com/angular-ui/ui-router ) to route to different states rather than specific urls.
Create a Service and reuse it wherever you want
Service
var App = angular.module('App', []);
App.service(function ($location) {
return {
a: function () {
$location.url('/a'); return;
},
b: function () {
$location.url('/b'); return;
},
c: function () {
$location.url('/c'); return;
},
d: function () {
$location.url('/d'); return;
},
e: function () {
$location.url('/e'); return;
},
f: function () {
$location.url('/f'); return;
}
};
});
How to use in a controller
App.controller(function($scope, RedirectService){
// call function a
RedirectService.a();
});
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.