Tat*_*ved 0 javascript angularjs angularjs-service angularjs-controller
在创建仪表板应用程序时,我遇到了需要将AngularJS控制器和服务集于一身的情况.
在主(第一)页面我有mainController(没有布局),也layoutController用方法loadLayoutFromAPI()和键绑定到按钮saveLayoutToAPI().
现在,在中学(第二)secondController只有而不是layoutController.我需要layoutController直接使用来自的方法secondController,我不想ng-controller在HTML中插入指令(而是secondController通过像服务一样的依赖注入).
MainPage(1st):
<div ng-controller="mainController">
<!-- some other code -->
<div ng-controller="layoutController as ctrl">
<a href="#" ng-click="ctrl.loadLayoutFromAPI()">Load</a>
<a href="#" ng-click="ctrl.saveLayoutToAPI()">Save</a>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
第二页(第二页):
<div ng-controller="secondController">
<!-- some other code -->
</div>
Run Code Online (Sandbox Code Playgroud)
我试图寻找这个问题,但根本找不到答案.
问题:我应该如何使用相同的代码(方法save()和load())作为Controller(ng-controller)和其他时间作为服务(包括在内dependency-injection)?
谢谢
JS Bin按要求
不要直接从其他控制器使用其他控制器的方法......这就是服务的原因.控制器只是在那里参与视图!
如果您想在控制器之间进行通信,或者指令或其他任何服务,工厂和提供商的用途.在构建任何应用程序时,您总是将常用功能抽象为某种服务
例如:
//Just an APP def
var app = angular.module('dashApp', []);
//LayoutController
app
.controller('layoutController', ['CtrlService', function(ctrlService){
this.saveLayoutToAPI = function(){
ctrlService.save();
}
this.loadLayoutFromAPI = function(){
ctrlService.load();
}
}]);
//Main Controller
app
.controller('mainController', function(){
//no work with layout at all
});
//Secondary controller
app
.controller('secondController', ['CtrlService', function(ctrlService){
this.save = function(){
ctrlService.save();
}
this.load = function(){
ctrlService.load();
}
}]);
app
.service('CtrlService', function () {
var obj = {
save: function () {
console.log('Layout saved.');
},
load: function () {
console.log('Layout loaded.');
}
}
this.save = obj.save;
this.load = obj.load;
});
Run Code Online (Sandbox Code Playgroud)