AngularJS DRY Controller 结构

标签 angularjs controller dry restangular

下面的代码表示在每个处理来自服务器的数据的 Controller 中重复相同的代码模式的情况。在#angularjs 上进行了长时间的研究和 irc 演讲后,我仍然无法弄清楚如何抽象该代码,内联注释解释了这种情况:

myApp.controller("TodoCtrl", function($scope, Restangular,
                                      CalendarService, $filter){
    var all_todos = [];
    $scope.todos = [];
    Restangular.all("vtodo/").getList().then(function(data){
        all_todos = data;
        $scope.todos = $filter("calendaractive")(all_todos);
    });
    //I can see myself repeating this line in every 
    //controller dealing with data which somehow relates
    //and is possibly filtered by CalendarService:
    $scope.activeData = CalendarService.activeData;
    //also this line, which triggers refiltering when
    //CalendarService is repeating within other controllers
    $scope.$watch("activeData", function(){
        $scope.todos = $filter("calendaractive")(all_todos);
    }, true);

});

//example. another controller, different data, same relation with calendar?
myApp.controller("DiaryCtrl", function($scope, Restangular,
                                       CalendarService, $filter){
    //this all_object and object seems repetitive,
    //isn't there another way to do it? so I can keep it DRY?
    var all_todos = [];
    $scope.todos = [];
    Restangular.all("diary/").getList().then(function(data){
        all_diaries = data;
        $scope.diaries = $filter("calendaractive")(all_diaries);
    });
    $scope.activeData = CalendarService.activeData;
    $scope.$watch("activeData", function(){
        $scope.todos = $filter("calendaractive")(all_diaries);
    }, true);
});

最佳答案

DRY 应该有目的地遵循,而不是狂热地遵循。您的代码很好, Controller 正在做他们应该做的事情:连接应用程序的不同部分。也就是说,您可以轻松地在返回函数引用的工厂方法中组合重复代码 .

例如,

myApp.factory('calendarScopeDecorator', function(CalendarService, Restangular, $filter) {
  return function($scope, section) {
    $scope.todos = [];
    $scope.activeData = CalendarService.activeData;
    Restangular.all(section+"/").getList().then(function(data){
      $scope.all_data = data;
      $scope.filtered_data = $filter("calendaractive")(data);
    });
    $scope.$watch("activeData", function(){
      $scope.todos = $filter("calendaractive")($scope.all_data);
    }, true);
  }
});

然后将其合并到您的 Controller 中:
myApp.controller("DiaryCtrl", function($scope, calendarScopeDecorator){
  calendarScopeDecorator($scope, 'diary');
});

关于AngularJS DRY Controller 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24676861/

相关文章:

javascript - 通过它在 Firebase 中的唯一 ID 查找对象

angularjs - Angular : Change component template using variables

javascript - 我无法通过angularjs中的指令更新变量

php - fatal error : Call to undefined function site_url()

ios - 为 UIViewController 中的 UIView 创建 Controller

仅在一个函数内重用代码的 Pythonic 方法

javascript - 在我的 jQuery 中重复函数,有更好的方法吗?

javascript - 单击表格行时,它会启用整个表格而不是一行,并且在选择获取值后取消定义

ruby-on-rails - 用于创建和更新的 DRY 表单部分

javascript - 如何在 Laravel 5.1 中将变量值从 JavaScript 发送到 Controller