此刻我正致力于巨大的角度SPA应用.我试着保持我的控制器很薄:
<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; } } } }
好处:
>逻辑不在控制器之外
缺点:
>服务变更范围状态
你保持控制器薄的方法是什么?
What is your approach to keep controllers thin?
我个人喜欢在工厂/服务中保留与应用程序模型相关的任何内容.因此,不会在控制器中定义代码中的remove和item.在控制器内部,我将设置对模型的引用,以满足指令的任何需要,即可通过$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); } } });
然后将模型传递给我的控制器:
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' });
等等