angularjs - 保持 Angular Controller 薄

标签 angularjs model-view-controller

目前我正在研究巨大的 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 之外

  • 缺点:
  • 服务更改范围状态

  • 您保持 Controller 瘦的方法是什么?

    最佳答案

    What is your approach to keep controllers thin?



    我个人喜欢在工厂/服务中保留与应用程序模型相关的任何内容。所以removeitem在您的代码中不会在 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/

    相关文章:

    php - 在我看来,代码是否太多了? CakePHP/MVC设计模式

    java - 在列表中使用图标代替元素符号点

    javascript - Angular 异步调用

    angularjs - 如何在AngularJS指令模板中动态定义要用ng-click调用的函数

    asp.net-mvc - ASP.Net MVC 强类型部分 View 和继承属性

    ios - 将 UIView 或结构数组传递给 UIViewController

    model-view-controller - 将 MVC (php) 框架与 CMS 集成

    javascript - 引用错误: jurusan is not defined in Angular with Nodejs

    javascript - 使用具有全局值的 Javascript Replace() 时 ng-bind-html 会中断

    angularjs - Sails/Angular 跨源请求被阻止