AngularJS data not being presented in view - javascript

I am new to AngularJS, and am working on my first Plunkr. When a user performs a search (from main.html, the corresponding controller is MainController), the correct view is being presented (user.html), but the data from the controller (UserController) is not being passed to the view. What am I doing wrong?
Here the link to the code:
http://plnkr.co/edit/OcfB6tBB36qWO9MiZ9CI?p=preview
Layout page (Index.html):
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="4.0.0" src="https://code.angularjs.org/latest/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="MainController.js"></script>
<script src="UserController.js"></script>
</head>
<body>
<h1>GitHub Viewer</h1>
<div ng-view></div>
</body>
</html>
Main page (main.html)
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" placeholder="User name to find" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
User details page (user.html)
<h1>{{ user.name }}</h1>
{{ error }}
<div><img src="{{ user.avatar_url }}" title="{{user.name}}"> Order:
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Stars</th>
<th>Repos</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td>{{ repo.name }}</td>
<td>{{ repo.stargazers_count | number}}</td>
<td>{{ repo.language }}</td>
</tr>
</tbody>
</table>
MainController.js - controls main.html:
var app = angular.module('githubViewer');
app.controller('MainController', function($scope, $http, $interval,
$log, $anchorScroll, $location) {
$scope.repoSortOrder = "-stargazers_count";
$scope.search = function(username) {
$log.info("Searching for " + username);
if(countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
$location.path("/user/" + username);
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
var decrementCountdown = function() {
$scope.countdown -= 1;
if($scope.countdown < 1) {
$scope.countdown = null;
$scope.search($scope.username);
}
};
$scope.username = "angular";
$scope.countdown = 5;
startCountdown();
});
UserController.js (controls user.html) -- this is where it seems to fail.
var app = angular.module('githubViewer');
app.controller("UserController", UserController);
var UserController = function($scope, $log, $http, $routeParams) {
var onUserComplete = function(response) {
$scope.user = response.data;
$http.get($scope.user.repos_url)
.then(onRepos, onError);
};
var onRepos = function(response) {
$scope.repos = response.data;
$location.hash("userDetails");
$anchorScroll();
};
var onError = function(reason) {
$scope.error = "Could not fetch the data";
};
$scope.username = $routeParams.username;
$scope.repoSortOrder = "-stargazers_count";
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
Any help will be appreciated.

Related

angularjs function not working to pull data from github api

I am new to AngularJs. It's a GitHub, datacontroller AngularJs program. Actually the data after using a controller, i.e checkbox is not coming and my ng-repeat is not working.
Can any anyone help me with this?
(function() {
var app = angular.module('app', []);
var mainController = function($scope, $http) {
$scope.message = "Angularjs";
$scope.reposortorder = "stargazers_count";
var onSuccess = function(response) {
$scope.obj = response.data;
$http.get($scope.obj.repos_url).then(onRepoSuccess, onError);
};
var onRepoSuccess = function(response) {
$scope.repos = response.data;
};
var onError = function(reason) {
$scope.error = "could not load the user details";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username).then(onSuccess, onError);
};
};
var checkbox = function($scope, $filter, $http) {
$http.get("https://api.github.com/users/"+$scope.username)
.success(function(data) {
$scope.repos = data;
});
$scope.chckedIndexs = [];
$scope.checkedIndex = function(repo) {
if ($scope.chckedIndexs.indexOf(repo) === -1) {
$scope.chckedIndexs.push(repo);
} else {
$scope.chckedIndexs.splice($scope.chckedIndexs.indexOf(repo), 1);
}
};
$scope.selectedRepos = function() {
return $filter('repo.name')($scope.repos, {
checked: true
});
};
$scope.remove = function(index) {
angular.forEach($scope.chckedIndexs, function(value, index) {
var index = $scope.repos.indexOf(value);
$scope.repos.splice($scope.repos.indexOf(value), 1);
});
$scope.chckedIndexs = [];
};
$scope.checkAll = function() {
angular.forEach($scope.repos, function(repo) {
repo.select = $scope.selectAll;
});
};
};
app.controller("mainController", mainController);
app.controller("checkbox", checkbox);
}())
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="mainController">
<h1>Hello {{message}}</h1>
{{username}}
<div>
<form name="searchUser">
<input type="search" required placeholder="Github Username to find" ng-model="username">
<input type="submit" value="Search" ng-click="search(username)">
</form>
<br />
<div>{{ error}}</div>
<p>Name: {{ obj.name }}</p>
<p>Mail id: {{ obj.email }}</p>
<p>Image:
<br /><img ng-src="{{ obj.avatar_url}}" height="150" title="{{ obj.name}} {{obj.lastName}}" /></p>
<div>
<label>Search:</label>
<input type="search" ng-model="searchrepo" placeholder="Enter to Search">
</div>
<div ng-controller="checkbox">
<p>
Sort by:
<select ng-model="reposortorder">
<option value="name">Name</option>
<option value="stargazers_count">Stars</option>
<option value="language">Language</option>
</select>
</p>
<div>
<pre>selected with helper function {{selectedRepos()}}</pre>
<button ng-click="remove($index)">delete selected</button>
</div>
<table border="1">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectAll" ng-click="checkAll"></th>
<th>Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos |filter:searchrepo | orderBy:reposortorder">
<td><input type="checkbox" ng-model="repo.checked" ng-click="checkedIndex(repo)"/></td>
<td>{{ repo.name }}</td>
<td>{{ repo.stargazers_count | number }}</td>
<td>{{ repo.language}}</td>
<td><button ng-click="remove($index)">x </button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Here is the plnkr link https://plnkr.co/edit/T3AK2QnIMq18oEeMuCQk?p=preview
<div ng-controller="table">
This line is reason of malfunctioning. You don't have any "table" controller. You bind repos in your mainController. Remove the "table" controller from that div, everything will work!
Thanks

Iterating over table using Angular

I'm new to angular and js. I did a table (just a header) and a button. When I click the button a new row line is added. Every cell of that row is a form text field. Everithing works fine. Now I'm trying to do a second button, when I click it must iterate over the rows and validate the fields. I'm not finding any documentation about that... so i'm not sure if this mettod (add a new row with a button) is appropiate. That's how I did it:
index.html this contains angular and my script, also contains the routes:
<html ng-app="assets">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="sources/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>
<script>
var assets = angular.module('assets', ['ngRoute']);
assets.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html'
}).
when('/:tipusactius', {
templateUrl: 'tipusactius.html',
controller: 'TipusActiusCtrl'
}).
when('/:tipusactius/alta', {
templateUrl: 'tipusactius-alta.html',
controller: 'AfegirTipusActiusCtrl'
}).
otherwise({
redirectTo: '/'
});
});
assets.controller('TipusActiusCtrl', function ($scope, $http){
$http.get('http://10.0.203.73/WS/ws.php/tipusactius/').success(function(data) {
$scope.tipus_actius = data;
});
// Ordena taula per id desc
$scope.sortField = 'idtipus_actius';
$scope.reverse = false;
});
assets.controller('AfegirTipusActiusCtrl', function ($scope, $http){
// Camps formulari text pla
$scope.nomAtribut = "<input type='text' name='firstname'>";
$scope.mida = "<input type='number' name='firstname'>";
$scope.obligatori = "<input type='checkbox' name='vehicle' value='yes'>";
// Construeix combo
$http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function(data) {
$scope.options = data;
});
$scope.atributs = [];
$scope.addField = function() {
$scope.atributs.push($scope.atributs.length);
};
$scope.prioritat = $scope.atributs.length;
});
assets.directive('compile', compile);
function compile($compile)
{
return {
restrict: 'A',
replace: true,
link: linkFunction
};
function linkFunction(scope, element, attrs)
{
scope.$watch(
function (scope)
{
return scope.$eval(attrs.compile);
},
function (value)
{
element.html(value);
$compile(element.contents())(scope);
}
);
}
}
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container" ng-view></div>
</body>
</html>
And this is the view where the table is(tipusactius-alta):
<div class="row">
<div class="col-md-8" ng-controller="AfegirTipusActiusCtrl">
<button ng-click="addField()">Nou atribut</button>
<div>
<table class="table">
<tr>
<td>Nom atribut</td>
<td>Tipus</td>
<td>Mida</td>
<td>Prioritat</td>
<td>Obligatori</td>
</tr>
<tr ng-repeat="atribut in atributs">
<td compile="nomAtribut"></td>
<td>
<select id="tipus">
<option ng-repeat="option in options" value="{{option.idvalors_combo}}">{{option.valor}}</option>
</select>
</td>
<td compile="mida"></td>
<td>
<select id="prioritat">
<option ng-repeat="p in prioritat" value="{{p}}">{{p}}</option>
</select>
</td>
<td compile="obligatori"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
I'm not sure if this has been a good idea. I would like to find a way to iterate over the rows to read cell values, and if the values of all cells from all the rows is ok submit the values to the web service but I have no idea. Any help will be great.
You don't actually need to manipulate html directly. Just use ng-repeat over your data collection. Button should add new items to that collection and angular will create new table row in the document.
I've created small sample here: http://jsfiddle.net/Lvc0u55v/252/
var myApp = angular.module('myApp', []);
myApp.controller('tableCtrl', function($scope) {
$scope.dataTable = [{
"name": "Alex",
"lastName": "Karlov",
"age": 23,
"sex": 1
}];
$scope.options = [{
"value": 1,
"title": "Male"
}, {
"value": 2,
"title": "Female"
}];
$scope.addRow = function() {
var newItem = {
name: "",
lastName: "",
age: "",
sex: ""
}
$scope.dataTable.push(newItem);
};
});
And this is the html (I've created it based on yours code):
<div class="col-md-8" ng-controller="tableCtrl">
<button ng-click="addRow()">Add row</button>
<div>
<table class="table">
<tr>
<td>#</td>
<td>Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
<tr ng-repeat="item in dataTable">
<td>{{ $index + 1 }}</td>
<td>
<input type="text" ng-model="item.name" />
</td>
<td>
<input type="text" ng-model="item.lastName" />
</td>
<td>
<input type="text" ng-model="item.age" />
</td>
<td>
<select ng-options="option.value as option.title for option in options" ng-model="item.sex"></select>
</td>
</tr>
</table>
</div>
</div>
In that sample I've put all my data into dataTable variable. When I want to add one more row, I just need to add new empty object (or with predefined values) into dataTable collection. Angular will do the trick.

Alert all checkboxes that are checked in ng-Repeat : AngularJS

I have a small program where I have 3 checkboxes. I may check any or all of the checkboxes. I will need to alert the names of the People infront of whose id I have checked the checkboxes.
HTML:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="(key,x) in People">
<td><input type="checkbox" id="{{x.id}}" >{{x.name}}</td>
</tr>
</table>
<button ng-click="alert()">Click</button>
<script>
//Module Declaration
var app = angular.module('myApp',[]);
//Controller Declaration
app.controller('myCtrl',function($scope){
$scope.checkboxArray = [];
$scope.People = [
{name:"Peter",id:"201"},
{name:"Lina",id:"202"},
{name:"Roger",id:"203"}
];
//alert function
$scope.alert = function(){
angular.forEach($scope.People, function(val,key) {
if('#val.id:checked'){
$scope.checboxArray + = $scope.People[key].name;
}
alert($scope.checkboxArray);
}
}
});
</script>
</body>
</html>
I am not sure if I am putting the condition properly inside if() condition. Can someone help?
You need to store the checked status using ng-model like below then find the checked items using the People array
var app = angular.module('my-app', [], function() {})
app.controller('AppController', function($scope) {
$scope.checkboxArray = [];
$scope.People = [{
name: "Peter",
id: "201"
}, {
name: "Lina",
id: "202"
}, {
name: "Roger",
id: "203"
}];
//alert function
$scope.alert = function() {
var selected = $scope.People.filter(function(item) {
return item.checked
}).map(function(item) {
return item.name;
})
alert(selected);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app">
<div ng-controller="AppController">
<table>
<tr ng-repeat="(key,x) in People">
<td>
<input ng-model="x.checked" type="checkbox" id="{{x.id}}">{{x.name}}</td>
</tr>
</table>
<button ng-click="alert()">Click</button>
<pre>{{People}}</pre>
</div>
</div>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="(key,x) in People">
<td><input type="checkbox" id="{{x.id}}" ng-model="x.checked">{{x.name}}</td>
</tr>
</table>
<button ng-click="alert()">Click</button>
<script>
//Module Declaration
var app = angular.module('myApp',[]);
//Controller Declaration
app.controller('myCtrl',function($scope){
$scope.checkboxArray = [];
$scope.People = [
{name:"Peter",id:"201", checked : false},
{name:"Lina",id:"202", checked : false},
{name:"Roger",id:"203", checked : false}
];
//alert function
$scope.alert = function(){
angular.forEach($scope.People, function(val,key) {
if(val.checked){
$scope.checboxArray.push(val.name);
} else{
alert(val.name ," is not checked");
}
}
}
});
</script>
</body>
</html>
Here's a working JSFIDDLE for your problem.
As Arun mentionned, the easiest way is to get the checked value using ng-model.
I updated your previous code and added my solution :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="x in People">
<td>
<input type="checkbox" ng-model="x.checked" id="{{x.id}}" >{{x.name}}<br/>
</td>
</tr>
</table>
<button ng-click="doAction()">Click</button>
<script>
//Module Declaration
var app = angular.module('myApp',[]);
//Controller Declaration
app.controller('myCtrl',function($scope){
$scope.People = [
{name:"Peter",id:"201", checked:"false"},
{name:"Lina",id:"202", checked:"false"},
{name:"Roger",id:"203", checked:"false"}
];
$scope.doAction = function() {
for(var x = 0;x < $scope.People.length;x++)
{
if ($scope.People[x].checked == true)
alert($scope.People[x].name);
}
}
});
</script>
</body>
</html>

pagination of my dataTable in angularJS

I have problem in pagination of my dataTable(angularJS),this is my code:
app.js:
.controller("StudentCtrl", ["$scope", "$http", "filterFilter", "$rootScope", "logger", "$filter", "$log", function($scope, $http, filterFilter, $rootScope, logger, $filter, $log) {
var init;
$scope.errors = [];
$scope.msgs = [];
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 1;
$http({method: 'GET', url: 'myURL'})
.success(function(data){
$scope.posts = data; // response data
$scope.searchKeywords = "", $scope.filteredStores = [], $scope.row = "", $scope.select = function(page) {
var end, start;
return start = (page - 1) * $scope.numPerPage, end = start + $scope.numPerPage, $scope.currentPageStores = $scope.filteredStores.slice(start, end);
}, $scope.onFilterChange = function() {
return $scope.select(1), $scope.currentPage = 1, $scope.row = "";
}, $scope.onNumPerPageChange = function() {
//console.log("2");
return $scope.select(1), $scope.currentPage =1 ;
}, $scope.onOrderChange = function() {
return $scope.select(1), $scope.currentPage;
}, $scope.search = function() {
return $scope.filteredStores = $filter("filter")(data, $scope.searchKeywords), $scope.onFilterChange();
}, $scope.order = function(rowName) {
return $scope.row !== rowName ? ($scope.row = rowName, $scope.filteredStores = $filter("orderBy")(data, rowName), $scope.onOrderChange()) : void 0;
}, $scope.numPerPageOpt = [3, 5, 10, 20], $scope.numPerPage = $scope.numPerPageOpt[2], $scope.currentPage = 1, $scope.currentPageStores = [], (init = function() {
return $scope.search(), $scope.select($scope.currentPage);
})()
}).error(function(data, status, headers, config) {
});
students.html
<div class="page page-table" ng-controller="StudentCtrl">
<section class="table-dynamic">
<div class="bs-component" >
<div class="bs-example table-dynamic">
<div class="table-filters">
<div class="row">
<div class="col-sm-4 col-xs-6">
<form>
<input type="text"
placeholder="search"
class="form-control"
ng-model="searchKeywords"
ng-keyup="search()" style="border-radius: 20px;">
</form>
</div>
<div class="col-sm-3 col-xs-6 filter-result-info">
<span>
Showing {{filteredStores.length}}/{{posts.length}} entries
</span>
</div>
</div>
</div>
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th >Nom</th>
<th >Prenom </th>
<th >DropOut </th>
<th >Live </th>
<th >Classe</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts">
<td align="center">{{post.LastName}}</td>
<td align="center">{{post.FirstName}}</td>
<td align="center">{{post.DropOut}}</td>
<td align="center">{{post.Live}}</td>
<td align="center">{{post.Class}}</td>
<footer class="table-footer">
<div class="row">
<div class="col-md-6 page-num-info">
<span>
Show
<select data-ng-model="numPerPage"
data-ng-options="num for num in numPerPageOpt"
data-ng-change="onNumPerPageChange()">
</select>
entries per page
</span>
</div>
<div class="col-md-6 text-right pagination-container">
<pagination class="pagination-sm"
page="currentPage"
total-items="filteredStores.length"
max-size="4"
on-select-page="select(page)"
items-per-page="numPerPage"
rotate="true"
boundary-links="true"
></pagination>
</div>
</div>
</footer>
</div></div></section></div>
this is what I get per example when I select 5 rows from all data(8 rows):
and this is when I clic on second page of paginator:(I get the 5 first items all the time not the rest of 8 rows)
so how can I set the informations in table rows from the paginator
thanks a lot for help
Update:jsfiddle code:
https://jsfiddle.net/1982ybj6/

items are displayed only after typing? Angular js

Almost everything working good beside 2 things
Code
var app = angular.module("MyApp", []);
app.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input.slice(start);
};
});
app.controller("MyControler", function($scope, $http, $filter) {
$http.get("http://127.0.0.1:8000/cars/?format=json").
success(function(data) {
$scope.list = data;
});
$scope.itemsPerPage = 1;
$scope.currentPage = 0;
$scope.items = [];
for (var i=0; i<50; i++) {
$scope.items.push({ id: i, name: "name "+ i, description: "description " + i });
}
$scope.range = function() {
var rangeSize = 3;
var ret = [];
var start;
start = $scope.currentPage;
if ( start > $scope.pageCount()-rangeSize ) {
start = $scope.pageCount()-rangeSize+1;
}
for (var i=start; i<start+rangeSize; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.prevPageDisabled = function() {
return $scope.currentPage === 0 ? "disabled" : "";
};
$scope.pageCount = function() {
return Math.ceil($scope.filtered.length/ $scope.itemsPerPage)-1;
};
$scope.nextPage = function() {
if ($scope.currentPage < $scope.pageCount()) {
$scope.currentPage++;
}
};
$scope.nextPageDisabled = function() {
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
};
$scope.setPage = function(n) {
$scope.currentPage = n;
};
var filterBy = $filter('filter');
$scope.$watch('search', function (newValue) { $scope.filtered = filterBy($scope.list, newValue); }, true);
});
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% verbatim %}
<div ng-app="MyApp" ng-controller="MyControler">
<table class="table table-striped">
<thead>
<tr>
<th><input ng-model="search.name" ></th>
<th><input ng-model="search.years"></th>
<th><input ng-model="search.owners"></th>
<th><input ng-model="search.accidents"></th>
<th><input ng-model="search.description"></th>
</tr>
<tr>
<th>Name</th>
<th>Years</th>
<th>Owners</th>
<th>Accidents</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cars in filtered| offset:currentPage*itemsPerPage | limitTo: itemsPerPage">
<td>{{cars.name}}</td>
<td>{{cars.years}}</td>
<td>{{cars.owners}}</td>
<td>{{cars.accidents}}</td>
<td>{{cars.description}}</td>
</tr>
</tbody>
<tfoot>
<td colspan="3">
<div class="pagination">
<ul>
<li ng-class="prevPageDisabled()">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range()" ng-class="{active: n == currentPage}" ng-click="setPage(n)">
{{n+1}}
</li>
<li ng-class="nextPageDisabled()">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
</table>
</div>
{% endverbatim %}
</body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="{% static 'js/app2.js' %}"></script>
</html>
My objects are displayed only when i start typing into filter field, as i see after pagination is updated actively with typing but then happening sth strange, pagination displayed also pages with minuses ?
So i would like to make items showed already without starting typing into filter and make these minuses disappear.
Thanks ;)
var app=angular.module('MyApp', []);
app.controller("MyControler", function($scope, $http, $filter) {
$http.get("http://127.0.0.1:8000/cars/?format=json").
success(function(data) {
$scope.list = data;
});
$scope.currentPage = 0;
$scope.pageSize = 1;
$scope.numberOfPages=function(){
var myFilteredData = $filter('filter')($scope.list, $scope.search);
return Math.ceil(myFilteredData.length/$scope.pageSize);
};
});
app.filter("offset", function() {
return function(input, start) {
start = +start;
return input.slice(start);
};
});
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% verbatim %}
<div ng-app="MyApp" ng-controller="MyControler">
<table>
<tr>
<th><input type="text" ng-model="search.name" class="form-control input-sm" placeholder="SEARCH" ></th>
<th><input type="text" ng-model="search.years" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.owners" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.accidents" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.description" class="form-control input-sm" placeholder="SEARCH"></th>
</tr>
<tr>
<th>Name</th>
<th>Years</th>
<th>Owners</th>
<th>Accidents</th>
<th>Description</th>
</tr>
<tr ng-repeat="cars in list | filter:search|offset:currentPage*pageSize | limitTo:pageSize">
<td>{{cars.name}}</td>
<td>{{cars.years}}</td>
<td>{{cars.owners}}</td>
<td>{{cars.accidents}}</td>
<td>{{cars.description}}</td>
</tr>
</table>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="(currentPage + 1) == numberOfPages()" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
{% endverbatim %}
</body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="{% static 'js/app2.js' %}"></script>
</html>
Solved

Categories