2015-01-07 8 views
1

Приветствуем всех и с нетерпением жду нового года!AngularJS, Ui-BootStrap и разбиение на страницы

Я изучаю AngularJS, чтобы использовать его для следующих профессиональных приложений, которые я разрабатываю в своей компании.

Я застрял с директивой разбиения на страницы из модуля ui-bootstrap. Атрибут total-items всегда не определен.

В моем примере я хочу отступить от Форума и разбивать страницы на темы из ресурсов. Я думаю, что директива разбиения на страницы не работает с отсроченными значениями ...

Помогите мне пожалуйста?

Вот служба:

var serverUrl = "http://localhost:8080/cocoon.backend/webresources"; 
angular 
     .module('cocoonApp') 
     .factory('ForumService', ['$resource','$q', function ($resource,$q) { 
       return { 
        getForum: function (forumId) { 
         var resource = $resource(serverUrl + '/forum/:forumId', {forumId: '@forumId'}); 
         return resource.get({forumId: forumId}); 
        }, 
        getTopics: function (forumId, page, nbResults) { 
         var resource = $resource(serverUrl + '/forum/:forumId/topic', {forumId: '@forumId'}); 
         return resource.query({forumId: forumId,page:page,nbResults:nbResults}); 
        } 

       }; 

      }]); 

Контроллер:

angular 
    .module('cocoonApp') 
    .controller('ForumController', 
      ['ForumService', '$stateParams', '$scope', '$log', '$q', function (service, $stateParams, $scope, $log, $q) { 

        $scope.currentForum = {}; 
        $scope.topicsToShow = []; 
        $scope.nbTopicsPerPage = 1; 
        $scope.currentPage = 1; 
        $scope.totalItems = 0; 

        $scope.init = function() { 
         $scope.currentForum = service.getForum($stateParams.forumID); 
         $scope.currentForum 
           .$promise 
           .then(function (data) { 
            $log.log(data); 
            $scope.totalItems = data.nbTopics; 
            $log.log('totalItems ' + $scope.totalItems); /*print the good number*/ 

           }) 
           .then(function() { 
            $scope.loadTopics(); 
           }); 
        }; 

        $scope.loadTopics = function() { 
         $log.log('Page changed to: ' + $scope.currentPage); 
         $scope.topicsToShow = service.getTopics($scope.currentForum.id, $scope.currentPage, $scope.nbTopicsPerPage); 
        }; 
       }]); 

И фрагмент HTML:

<!DOCTYPE html> 

<div class="content" ng-controller="ForumController" ng-init="init()"> 


    <div class="content" > 


     <a ui-sref="forum({forumID:currentForum.parent.id})"> 
      <h2> 
       <i class="icon-arrow-left"></i> 
       {{currentForum.parent.title}}   
      </h2> 
     </a> 

     <h1> 
      {{currentForum.title}}   
     </h1> 

     <div ng-repeat="child in currentForum.sousForums" > 
      <a ui-sref="forum({forumID:{{child.id}}})"> 
       <h2> 
        <i class="icon-arrow-right"></i> 
        {{child.title}}   
       </h2> 

      </a> 
     </div> 
    </div> 


    <div class="container"> 
     <h4>{{currentForum.nbTopics}} Topics</h4> 
     <table class="table-responsive table-topics"> 
      <thead> 
       <tr> 
        <th> 
         Id 
        </th> 
        <th> 
         Topic 
        </th> 
        <th> 
         Autor 
        </th> 
        <th> 
         Nb messages 
        </th> 
        <th> 
         Last message 
        </th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr topic-summary ng-model="topicsToShow" ng-repeat="topic in topicsToShow"></tr> 
      </tbody> 
     </table> 
     <pagination total-items="totalItems" ng-model="currentPage" ng-change="loadTopics()" ></pagination> 

    </div> 

</div> 

Большое спасибо

PS: Объект JSON получено:

{"type":"forumDTO","id":4,"parent":{"type":"forumDTO","id":3,"sousForums":[],"title":"Forum"},"nbTopics":3,"sousForums":[],"title":"MANGAS"} 
+0

ли ваш получать какое-либо значение для $ scope.currentForum.nbTopics в обработчике успеха, где вы назначаете это значение $ scope.totalItems? –

+0

Да, я получаю реальный номер, который мне нужен. Если я напечатаю его в методе then(), я получаю хорошее значение. Кажется, что директива обрабатывается до конца then(), и я не знаю, как заставить ее ждать. –

ответ

1

Ваш результат от службы будет служить аргументом в обработчике успеха. Вы можете написать функцию инициализации, как это:

    $scope.init = function() { 
         $scope.currentForum = service.getForum($stateParams.forumID); 
         $scope.currentForum 
           .$promise 
           .then(function (result) { 
            $scope.totalItems = result.nbTopics; 
           }).then(function() { 
          $scope.loadTopics(); 
         }); 
        }; 
+0

Я уже пробовал это. Я отредактирую сообщение, чтобы включить ваше предложение. –

+0

Возможно, $ scope внутри then() не то же самое, что и $ scope. –

+0

В идеале это не должно, но если где-то создается новый объект в вашем коде, вы можете создать объект-оболочку, например $ scope.wrapper = {totalItems: 0}, а в html write total-items = "wrapper.totalItems" и присвойте $ scope.wrapper.totalItems = data.nbTopics в вашем обработчике успеха. Можете ли вы попробовать это однажды? –