【问题标题】:Angular: Staying DRY With Angular-UI Pagination?Angular:使用 Angular-UI 分页保持干燥?
【发布时间】:2014-06-26 02:01:25
【问题描述】:

我在与不同控制器交互的多个视图上使用 angular-ui:bootstrap 分页指令;这些视图/控制器通常必须与排序和过滤进行交互,这需要动态更新页面大小,例如:

              <pagination 
                on-select-page="setPage(page)" 
                items-per-page="pageSize" 
                boundary-links="true" 
                total-items="totalItems" 
                page="search.page" 
                max-size="maxVisiblePages" 
                class="pagination-sm"
                num-pages="numPages"
                previous-text="&lsaquo;" 
                next-text="&rsaquo;" 
                first-text="&laquo;" 
                last-text="&raquo;" 
                >
              </pagination>

在我的每个控制器中,我必须重新定义这些 $scope 函数,例如:

      $scope.setPage = (page) ->
        $timeout ->
          $scope.search.page = page if $scope.search.page isnt page
          $scope.totalItems = $scope.matchedItems.length
          startIndex = (page - 1) * $scope.pageSize
          $scope.images = $scope.matchedItems.slice(startIndex, startIndex + $scope.pageSize)
          return
      $scope.sortMatches = ->
        $scope.matchedItems= $filter("orderBy")($scope.matchedItems, ['type','name'], true)
        $scope.setPage 1
        return
       ...

在避免控制器和视图中的代码重复的同时,为我提供这种排序/过滤/分页功能的最佳方式是什么?我在想我可以创建一个安装$scope 函数的类和另一个包装&lt;pagination&gt; 指令的指令,但我不知道这是否是最佳选择。

【问题讨论】:

    标签: angularjs coffeescript angularjs-directive angular-ui-bootstrap


    【解决方案1】:

    Angular 的一般规则是,如果您需要共享代码,它要么是服务,要么是工厂。对于您的情况,我会提供服务。例如,我有一个在多个控制器中使用的“取消”服务:

      module.service "cancelService", ($location) ->
        @cancel = ->
          if (/#/.test($location.$$path))
            $location.path($location.$$path.replace(/#.*/, "##{moment()}"))
          else
            $location.path($location.$$path += "#" + moment());
        @
    
      module.controller('adminUserEdit', ["$scope", '$route',"$location", '$stateParams', "userService",'roleService', 'cancelService', ($scope, $route, $location, $stateParams, userService, roleService, cancelService) -> 
        $scope.cancel = cancelService.cancel
    

    这样我就可以将 cancelService 函数拉入任何需要取消操作的控制器中。

    【讨论】:

    • 那么您是否建议我将 $scope 注入服务并添加使用它来定义常用功能?
    • 不,我认为情况正好相反。将公共代码保留在服务中,然后在控制器代码中附加指向这些函数的指针。相关:stackoverflow.com/questions/15509457/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2021-04-12
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多