目前我正在研究巨大的 Angular SPA 应用程序。我尽量保持我的 Controller 瘦:
<div ng-controller='HomeController as home'>
<div ng-repeat='var item in home.items' ng-bind='item' ></div>
<button ng-click='home.remove(1)' >remove</button>
</div>
function HomeController (homeService){
var vm = this; //$scope
vm.items = [1,2,3,4,5];
vm.remove = remove;
function remove (id){
homeService.remove({ items: vm.items, targetId: id });
}
//a lot of other logic here
}
angular.module('my').service('homeService', homeService);
function homeService (){
this.remove = remove;
function remove (param){
for(var a = 0; a < param.items.length; a++){
if(param.items[a] == param.targetId){
param.items.splice(a, 1);
break;
}
}
}
}
好处:
缺点:
您保持 Controller 瘦的方法是什么?
最佳答案
What is your approach to keep controllers thin?
我个人喜欢在工厂/服务中保留与应用程序模型相关的任何内容。所以
remove
和 item
在您的代码中不会在 Controller 中定义。在 Controller 内部,我将设置对模型的引用,以获取指令所需的任何内容,即可通过 $scope
访问.例如,考虑一个具有实体数组和方法的模型,用于在数组中添加/删除/查找实体。我将首先创建一个工厂,公开我的模型和方法来使用它:
angular.module('myApp').factory('model', function() {
// private helpers
var add = function(array, element) {...}
var remove = function(array, element) {...}
var find = function(array, id) {...}
return {
Entity: function(id) {
this.id = id;
},
entities: {
entities: [],
find: function(id) {
return find(this.entities, id);
},
add: function(entity) {
add(this.entities, entity);
},
remove: function(entity) {
remove(this.entities, entity);
}
}
});
然后将模型传递给我的 Controller :
angular.module('myApp').controller('ctrl', function($scope, model) {
$scope["model"] = model; // set reference to the model if i have to
var entity = new model.Entity('foo'); // create a new Entity
model.entities.add(entity); // add entity to entities
model.entities.find('foo'); // find entity with id 'foo'
});
等等。
关于angularjs - 保持 Angular Controller 薄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30275501/