我有两个控制器
user.controller.js:
const fetchApi = () => {
console.log('fetching');
};
fetchApi();
我想打电话给我dashboard.controller.js此功能,而无需再次写在仪表盘控制器此相同的硬编码。
答案 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>