在两个控制器中都调用一个函数-AngularJS 1.x

时间:2019-01-29 05:34:15

标签: javascript angularjs

我有两个控制器

user.controller.js:

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

fetchApi();

我想打电话给我dashboard.controller.js此功能,而无需再次写在仪表盘控制器此相同的硬编码。

1 个答案:

答案 0 :(得分: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>

编辑:注入服务

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>