0

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 ?

qazzu
  • 361
  • 3
  • 5
  • 16

4 Answers4

0

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();

Vivek
  • 11,938
  • 19
  • 92
  • 127
0

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:

https://docs.angularjs.org/guide/providers

Zeb
  • 2,687
  • 7
  • 28
  • 36
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0
(angular.module('myApp', [])
    .factory('alertFactory', alertFactory);
    .controller('alertCtrl', alertCtrl);

function alertFactory () {
    return {
        alertMessage : function(){
        alert("user");
    }
}

alertCtrl.$inject = ['alertFactory'];
function alertCtrl(alertFactory){
    alertFactory.alertMessage();
})();
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
0

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
        }
    }
}
soote
  • 3,240
  • 1
  • 23
  • 34