我们目前有一个项目,我们将很快扩大规模。我正在重构项目,以确保它在长期内更易于维护,并且对于刚刚参与该项目的人来说并不是一个彻头彻尾的头痛。
请忽略下面的任何语法错误,我必须更改一些代码以尝试最好地说明架构问题。
我们试图尽可能地遵循约翰爸爸风格指南。
目前我们的设置如下:
的PageController
(function() {
'use strict';
angular
.module('front')
.controller('PageController', PageController)
/** @ngInject */
function PageController($rootScope, $scope, $timeout, toastr, dataService, allowed, Pusher) {
var vm = this;
vm.allowed = allowed;
vm.widget = {
};
activate();
function activate(){
getOurWidgetData();
} // end activate()
/* get widget data */
function getOurWidgetData() {
dataService.getData(
$rootScope.wf.api + '/endpoint',
function(response) {
vm.widget.data = response.data.data;
vm.widgetlastModified = new Date(response.data.timestamp * 1000);
},
function(error) {
vm.widget.error = error;
}
);
}
vm.getOurWidgetData = getOurWidgetData;
}
})();
在我们的PageController视图中:
<div class="col-xs-12 col-md-4">
<div class="panel">
<div class="panel__header">
<h2><span>Widget</span>
<last-updated last-updated="main.widget.lastModified" lu-error="main.widget.error" label="As at"></last-updated>
</h2>
</div>
<div class="panel__body">
<div our-widget="" our-data="main.widget.data"></div>
</div>
</div>
</div>
然后在OurWidget中:
(function() {
'use strict';
angular
.module('front')
.directive('ourWidget', ourWidget);
/** @ngInject */
function ourWidget() {
var directive = {
restrict: 'A',
templateUrl: 'app/components/ourWidget/ourWidget.html',
scope: {
aumData: '='
},
controller: ourWidgetController,
controllerAs: 'ow',
bindToController: true
};
return directive;
/** @ngInject */
function ourWidgetController() {
var vm = this;
activate();
function activate() {
}
}
}
})();
现在,这个指令/组件很空。此时我的建议是将dataService调用从PageController移动到组件中。
因此,ourWidget指令如下所示:
(function() {
'use strict';
angular
.module('front')
.directive('ourWidget', ourWidget);
function ourWidget() {
var directive = {
restrict: 'E',
templateUrl: 'app/components/ourWidget/ourwidget.html',
scope: {
ourModel: '='
},
controller: ourWidgetController,
controllerAs: 'ow',
bindToController: true
};
return directive;
/** @ngInject */
function ourWidgetController($rootScope, dataService, constants, endpoints, $log) {
var vm = this;
vm.OurWidget = {};
activate();
function activate() {
getOurWidgetData();
} // end activate()
function getOurWidgetData() {
dataService.getData(
constants.apiv2 + endpoints.OurWidget,
function(response) {
$log.log(response);
vm.OurWidget.data = response.data.data;
vm.OurWidget.lastModified = new Date(response.data.timestamp * 1000);
},
function(error) {
vm.OurWidget.error = error;
}
);
}
vm.getOurWidgetData = getOurWidgetData;
}
}
})();
我有这个原型并且它完美无缺,这意味着我有一个html标签,如:
<our-widget></our-widget>
我可以把它放在应用程序的任何地方我需要它。该指令现在负责其数据,这意味着我们不会在任何需要该组件的页面控制器上复制粘贴dataService调用。
我的问题是,这是一种更好的方法吗,在组件/指令中调用dataService而不是PageController?我会说是,因为我们之前的方法直接违反DRY原则。虽然有些人认为它违背了Angular风格指南,但是我没有看到任何例子或建议不以这种方式做到这一点,或者实际上任何暗示这种项目架构除了让dataService处理我们已经拥有的所有http请求。
是的,我注意到我们错误地使用了$ rootScope,我正试图解决这些问题,因为我正在进行:)