Edit:Laravel 4 и угловые JS и Twitter Bootstrap 3 Разбивка
мне нужна пагинация в моих Laravel 4 - Угловые применений JS, который структурирован с использованием Twitter Bootstrap 3. Вы можете предложить angularui-bootstrap pagination. Но я не планирую использовать это прямо сейчас. Мне нужно исследовать и использовать функции разбивки страницы Laravel с помощью angular.js. Я видел один блог article here, который описывает то же самое. Но моя неудача, она не работает, и в статье много ошибок.
Итак, на основе этой статьи у меня есть функция контроллера Laravel, которая использует pagination, как это, пожалуйста, не то, что я преобразовываю свои данные возврата в массив, используя toArray()
.
class CareerController extends BaseController {
public function index() {
$careers = Career::paginate($limit = 10);
return Response::json(array(
'status' => 'success',
'message' => 'Careers successfully loaded!',
'careers' => $careers->toArray()),
200
);
}
}
Теперь посмотрим, как он будет загружен данные в моей Firebug консоли с помощью angularjs REST HTTP $resource
вызов,
Здесь у меня есть некоторые детали разбивки на страницы, такие как total
, per_page
, current_page
, last_page
, from
и to
включая мои data
.
А теперь посмотрим, что я делаю в угловом скрипте
var app = angular.module('myApp', ['ngResource']); // Module for the app
// Set root url to use along the scripts
app.factory('Data', function(){
return {
rootUrl: "<?php echo Request::root(); ?>/"
};
});
// $resource for the career controller
app.factory('Career', [ '$resource', 'Data', function($resource, Data) {
return $resource(Data.rootUrl + 'api/v1/careers/:id', { id: '@id'}, {
query: {
isArray: false,
method: 'GET'
}
});
}]);
// the career controller
function CareerCtrl($scope, $http, Data, Career) {
// load careers at start
$scope.init = function() {
Career.query(function(response) {
$scope.careers = response.careers.data;
$scope.allCareers = response.careers;
}, function(error) {
console.log(error);
$scope.careers = [];
});
};
}
И мой взгляд,
<div class="col-xs-8 col-sm-9 col-md-9" ng-controller="CareerCtrl" data-ng-init="init()">
<table class="table table-bordered">
<thead>
<tr>
<th width="4">S.No</th>
<th>Job ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="career in careers">
<td style="text-align:center">{{ $index+1 }}</td>
<td>{{ career.job_id }}</td>
<td>{{ career.job_title }}</td>
</tr>
<tr ng-show="careers.length == 0">
<td colspan="3" style="text-align:center"> No Records Found..!</td>
</tr>
</tbody>
</table>
<div paginate="allCareers"></div>
</div><!--/row-->
И директива постраничной,
app.directive('paginate', [ function() {
return {
scope: { results: '=paginate' },
template: '<ul class="pagination" ng-show="totalPages > 1">' +
' <li><a ng-click="firstPage()">«</a></li>' +
' <li><a ng-click="prevPage()">‹</a></li>' +
' <li ng-repeat="n in pages">' +
' <a ng-bind="n" ng-click="setPage(n)">1</a>' +
' </li>' +
' <li><a ng-click="nextPage()">›</a></li>' +
' <li><a ng-click="last_page()">»</a></li>' +
'</ul>',
link: function(scope) {
var paginate = function(results) {
if (!scope.current_page) scope.current_page = 0;
scope.total = results.total;
scope.totalPages = results.last_page;
scope.pages = [];
for (var i = 1; i <= scope.totalPages; i++) {
scope.pages.push(i);
}
scope.nextPage = function() {
if (scope.current_page < scope.totalPages) {
scope.current_page++;
}
};
scope.prevPage = function() {
if (scope.current_page > 1) {
scope.current_page--;
}
};
scope.firstPage = function() {
scope.current_page = 1;
};
scope.last_page = function() {
scope.current_page = scope.totalPages;
};
scope.setPage = function(page) {
scope.current_page = page;
};
};
var pageChange = function(newPage, last_page) {
if (newPage != last_page) {
scope.$emit('page.changed', newPage);
}
};
scope.$watch('results', paginate);
scope.$watch('current_page', pageChange);
}
}
}]);
Теперь я получаю максимум 10 записей в моей таблице html, ссылки на страницы не работают.
Консоль показывает Error: results is undefined
с директивой разбиения на страницы.
plunker или скрипку будет очень полезно. –
Попробуйте инициализировать свойство «карьеры» в начале функции «CareerCtrl»: 'CareerCtrl ($ scope, $ http, Data, Career) {$ scope.careers = []; ... ' – Alexei
Можете ли вы сделать свой http://azureits.com/cms/api/v1/careers/ return Content Type« application/json »? – marcoseu