I have a 2 controllers and I have a same function that is declared inside the two controllers.
My function is:
$scope.users = function() {
alert("user")
};
My question is how can I declared it once. Repeatable code is not good ?
I have a 2 controllers and I have a same function that is declared inside the two controllers.
My function is:
$scope.users = function() {
alert("user")
};
My question is how can I declared it once. Repeatable code is not good ?
You can define a factory like
app.factory('ShowAlertFactory', function(){
return {
showAlertMessage : function(){
alert("user");
}
}
});
Now you can inject this ShowAlertFactory in any controller and call ShowAlertFactory.showAlertMessage();
You should declare your common functions in a service or factory and then inject it into your controllers
Factory Code
var app = angular.module('myApp', []);
app.factory('alertFactory', function() {
return {
alertMessage : function(){
alert("user");
}
}
To inject the factory, try this
app.controller('myCtrl', ['alertFactory', function(alertFactory) {
});
Reference:
(angular.module('myApp', [])
.factory('alertFactory', alertFactory);
.controller('alertCtrl', alertCtrl);
function alertFactory () {
return {
alertMessage : function(){
alert("user");
}
}
alertCtrl.$inject = ['alertFactory'];
function alertCtrl(alertFactory){
alertFactory.alertMessage();
})();
Adding this code to a factory will suffice if you are only duplicating the js. However if you are also duplicating html, a better way to handle this situation is with a directive.
Try identifying if the html is also being duplicated, and utilize directives if that is the case.
app.directive('myDirective', function() {
return {
template: "html common to both controllers",
link: function() {
// js common to both controllers
}
}
}