0

I have two controllers

user.controller.js:

const fetchApi = () => {
  console.log('fetching');
};

fetchApi();

I want to call this function in my dashboard.controller.js without writing this same hard code in dashboard controller again.

1 Answer 1

1

var app = angular.module('myapp', []);

var fetchApi = function($scope){
   console.log("fetching");
};
fetchApi.$inject = ['$scope'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="dashboardCtrl"></div>
<div ng-controller="homeCtrl"></div>
</div>

EDIT : inject service

var app = angular.module('myapp', []);

var fetchApi = function($scope, RestService){
 console.log("fetching");
 RestService.getUser();
};
fetchApi.$inject = ['$scope', 'RestService'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);

app.service('RestService', ['$http',
 function($http){
    this.getUser = function() {
        //$http api call
        console.log("get user");
    }
 }
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app="myapp">
    <div ng-controller="dashboardCtrl"></div>
    <div ng-controller="homeCtrl"></div>
    </div>

Sign up to request clarification or add additional context in comments.

3 Comments

is this called "service" ?
No, This so not a service . is a simple controller function. for service docs.angularjs.org/guide/services
Can you update your answer with services approach? i am looking for service method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.