I have an issue in the Edit Part of a Simple Angular Todo App That I created.
My App Adds, deletes and Edits an Entry. I have used AngularJS and BootStrap for this.
The prolem is, when I press edit button, all the entries, get into edit mode instead of the entry that I want to edit.
I am not sure why the in place edit is not working as expected.
My HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="../bower_components/angular/angular.min.js"></script>
<script src="todo.js"></script>
</head>
<body ng-controller="myCtrl">
<div class="container">
<h1>My TODO List</h1>
<table class="table">
<thead>
<tr>
<td><input class="form-control" ng-model="todo"></td>
<td><button class="btn btn-primary" ng-click="addItem()">Add</button></td>
</tr>
<tr>
<th>Serial No</th>
<th>Tasks to be Completed</th>
<th>Action</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="todo in todolist">
<td >{{$index+1}}</td>
<td ng-hide="todo.selected == true">{{todo.task}}</td>
<td><input class="form-control" ng-show="todo.selected == true" ng-model="todo.task">
<button class="btn btn-success" ng-show="todo.selected == true" ng-click="save($index)">Save</button>
<button class="btn btn-danger" ng-show="todo.selected == true" ng-click="cancel($index)">Cancel</button>
<button class="btn btn-warning" ng-click="edit($index)" ng-hide="todo.selected == true">Edit</button>
<button class="btn btn-danger" ng-click="deleteItem($index)" ng-hide="todo.selected == true">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
My JavaScript Code:
angular.module("myApp",[])
.controller("myCtrl", function($scope){
$scope.todolist = [];
$scope.addItem = function(){
console.log($scope.todo);
if($scope.todo === undefined){
return false ;
}
else{
$scope.todoObj = {};
$scope.todoObj["task"] = $scope.todo;
$scope.todoObj["selected"] = false;
$scope.todolist.push($scope.todoObj);
$scope.todo = "";
console.log($scope.todolist);
}
}
$scope.deleteItem = function($index){
var index =$index;
$scope.todolist.splice(index,1);
}
$scope.edit = function($index){
for(var i=0; i< $scope.todolist.length; i++)
if($index == i){
$scope.todolist[i].selected = true;
}
}
$scope.save = function($index){
console.log("saving contact");
console.log($scope.todolist.length)
for(var i=0; i< $scope.todolist.length; i++){
if($index == i){
console.log($scope.todolist[$index]);
$scope.todolist[i] = `enter code here`angular.copy($scope.todolist[$index]);
// $scope.todolist[i] = $scope.todolist[$index];
$scope.todolist[i].selected = false;
console.log("todo after save",$scope.todolist);
}
}
}
$scope.cancel = function($index) {
for(var i=0; i< $scope.todolist.length; i++){
if ($scope.todolist[$index].selected !== false) {
$scope.todolist[$index].selected = `enter code here`$scope.todolist[i];
$scope.todolist[$index].selected = false;
}
}
};
})
When you are setting this
$scope.editing = $scope.todolist.indexOf(item);
All of your ng-repeats are relying on this to hide/show themselves.
ng-show="editing"
Related
I have a set of table columns. Each column can be sorted straight and in reverse. Up until now, we were doing that sorting inside each ng-click and ng-show, like so:
HTML
<a style="color:black" href="" ng-click="sortReverse = !sortReverse; changeSortType('id')">
Group id
<span ng-show="sortType == 'id' && !sortReverse" class="fa fa-caret-down"></span>
<span ng-show="sortType == 'id' && sortReverse" class="fa fa-caret-up"></span>
</a></th>
CONTROLLER
$scope.sortType = 'count';
$scope.sortReverse = true;
$scope.changeSortType = function (sortType){
$scope.sortType = sortType;
};
$scope.itemSortValue = function (item) {
return Service.sort(item, $scope.sortType)
};
Now we want to replace this with a method, that does the same so we can diminish the amount of code in the HTML.
I don't know how to do this exactly in AngularJS. Whatever I do doesn't work. I have also seen a couple of answers but they don't work, or I am doing something wrong. COuld you please help me with the code.
For <a> element remove sortReverse = !sortReverse; from ng-click and add $scope.sortReverse= !$scope.sortReverse it in the first line of method changeSortType;
and for ng-show create and method
$scope.myMethod = function (id, reverse){
return id && reverse;
};
and change html to
<span ng-show="myMethod('id',!sortReverse)" class="fa fa-caret-down"></span>
<span ng-show="myMethod('id',sortReverse)" class="fa fa-caret-up"></span>
Try with this code .
Html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<div class="jumbotron bg-dark" style="border-radius: 0px; margin-bottom: 0px;">
<h1 class="text-center" style="color:azure;">Table Sort</h1>
</div>
<table class="table table-dark table-striped">
<thead>
<tr>
<th ng-click="orderByMe('Name')" style="cursor: pointer;">Name <i class="fa fa-sort-desc" style="font-size:15px;color: whitesmoke" ng-if=" toggleCursor == 'desc'"></i> <i class="fa fa-sort-asc" ng-if=" toggleCursor == 'asc'"></i></th>
<th style="cursor: pointer;">City </th>
<th style="cursor: pointer;"> Country</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" data in myData | orderBy:myOrderBy">
<th>{{data.Name}}</th>
<th>{{data.City}}</th>
<th>{{data.Country}}</th>
</tr>
</tbody>
</table>
</div>
</body>
</html>
JS File
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://www.w3schools.com/angular/customers.php").then(function(response) {
$scope.myData = response.data.records;
});
$scope.toggleCursor = 'desc';
$scope.myOrderBy = 'Name';
$scope.orderByMe = function(sort) {
$scope.myOrderBy = sort;
$scope.sortArry = $scope.myData.sort();
if($scope.toggleCursor == 'desc')
{
$scope.toggleCursor = 'asc';
$scope.myOrderBy = $scope.sortArry;
}
else
{
$scope.toggleCursor = 'desc';
$scope.myOrderBy = $scope.sortArry.reverse();
}
}
});
before saving data in localstorage I have to verify whether user fill all the inputs.everything work fine with the exeption of input validation. up to the moment i'm not good familiar with the Angularjs.
any help highly appreciated
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.d1 = [];
$scope.d2 = [];
$scope.data = [];
$scope.append = function() {
$scope.data.push([]);
};
$scope.save = function() {
for (var i = 0; i < $scope.d1.length; i++) {
if ($scope.d1[i].length === 0) {
alert("fill empty fields please");
} else {
localStorage.setItem('Surname', JSON.stringify($scope.d1));
}
}
for (var j = 0; j < $scope.d2.length; j++) {
if ($scope.d2[j].length === 0) {
alert("fill empty fields please");
} else {
localStorage.setItem('Name', JSON.stringify($scope.d2));
}
}
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="container">
<div class="btn-group">
<button ng-click="append()" type="button" class="btn btn-default">append</button>
<button ng-click="save()" type="button" class="btn btn-default">Save</button>
</div>
<table class="table table-bordered">
<tr>
<th>Surname</th>
<th>Name</th>
</tr>
<tr ng-repeat="x in data">
<td><input ng-model="d1[$index]" type="text" class="form-control"></td>
<td><input ng-model="d2[$index]" type="text" class="form-control"></td>
</tr>
</table>
</div>
</body>
</html>
Add element Name in input and use 'required' to make the field mantatory
<form name="myForm" novalidate>
..........................
<td><input ng-model="d1[$index]" type="text"
required name="text{{$index}}" class="form-control"></td>
<td><input ng-model="d2[$index]"
type="text" required name="text{{$index}}"class="form-control"></td>
........</form>
Before doing save operation check weather form valid or invalid
$scope.save = function() {
if($scope.myForm.$valid){
//add code
}else{
//display error message
}
}
We can display field level validation also Please refer here
Here, I'm trying to insert a tr tag under a selected tr tag.I managed to insert the tr in the table but it was in the bottom.
This is a sample code:
"use strict";
(function(angular) {
var app = angular.module('app', []);
app.controller('MainController', MainController);
MainController.$inject = ['$compile', '$scope', '$templateCache'];
function MainController($compile, $scope, $templateCache) {
var publishShown = false;
var lastItemAppned;
var vm = this;
vm.targets = ['Single passenger', 'Single driver', 'All passengers', 'All drivers'];
vm.items = ["Cheese", "Pepperoni", "Black Olives"];
vm.cancel = cancel;
vm.fruits = [{
name: 'Orange',
color: 'Orange',
tree: 'Orange Tree!',
origin: 'China'
}, {
name: 'Apple',
color: 'Green',
tree: 'Apple Tree!',
origin: 'Moon'
}];
vm.message = 'Fruit store!';
function appendTemplate(event) {
if (publishShown) {
removeLastAppend();
}
publishShown = true;
var template = $templateCache.get('template.html');
var compiledHtml = $compile(template)($scope);
var parent = event.currentTarget.parentElement.parentElement.parentElement;
parent.append(compiledHtml[0]);
}
vm.showOptions = function(event) {
appendTemplate(event);
}
function removeLastAppend() {
angular.element('#publish-template').remove();
}
function cancel() {
removeLastAppend();
}
}
})(window.angular);
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap-css#3.*" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
<link data-require="bootstrap#*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
<script data-require="jquery#*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="Tether#*" data-semver="1.4.0" src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script data-require="bootstrap#*" data-semver="4.0.5" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
<script data-require="angularjs#1.6.*" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<script data-require="angular-animate#1.6.*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-animate.js"></script>
<script data-require="angular-touch#1.6.*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-touch.js"></script>
<script data-require="ui-bootstrap#*" data-semver="2.5.0" src="https://cdn.rawgit.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-2.5.0.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController as vm">
<script type="text/ng-template" id="template.html">
<tr id="publish-template">
<td colspan="5">
<div class="row">
<div class="col-sm-3">
<button class="btn btn-sm btn-success" ng-click="vm.command()">Command</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-primary" ng-click="vm.sell()">Sell</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-warning" ng-click="vm.eatSome()">Eat some!</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-danger" ng-click="vm.cancel()">Cancel</button>
</div>
</div>
</td>
</tr>
</script>
<div class="container-fluid">
<h1>{{vm.message}}</h1>
<table class="table">
<thead>
<th>Name</th>
<th>Color</th>
<th>Tree</th>
<th>Origin</th>
<th>Action</th>
</thead>
<tbody>
<tr ng-repeat="fruit in vm.fruits">
<td>{{fruit.name}}</td>
<td>{{fruit.color}}</td>
<td>{{fruit.tree}}</td>
<td>{{fruit.origin}}</td>
<td>
<button class="btn btn-primary" ng-click="vm.showOptions($event)">Options</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
As you see, if you click the second options button, you'll not notice the problem, but if you click the first one, it adds a tr tag always in the bottom of the table!
My aim is to add the new tr under the selected on.
Thanks in advance
The ng-repeat is running on the tr element and you are looking to break the loop and insert another tr in the middle based on the row that was clicked on. To achieve this you need to break the table into 3 parts
TR ng-repeat on topFruits
TR row with option buttons (will be hidden initially)
TR ng-repeat on bottomFruits
Initially, you will need to assign all the fruits to topFruits and keep the bottomFruits null. Also keep the tr row with the option buttons hidden.
When the show Options button is clicked on a row, get the index of the row and then divide the fruits between topFruits and bottomFruits based on the index. Also make the row with buttons visible.
Here is a working demo
Here is the HTML body
<body ng-controller="MainCtrl as vm">
<div class="container-fluid">
<h1>{{vm.message}}</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Tree</th>
<th>Origin</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="fruit in vm.topFruits">
<td style="background:#bbb">{{fruit.name}}</td>
<td>{{fruit.color}}</td>
<td>{{fruit.tree}}</td>
<td>{{fruit.origin}}</td>
<td>
<button class="btn btn-primary" ng-click="vm.showOptionsTop($index)">Options</button>
</td>
</tr>
<tr id="publish-template" style="display:none">
<td colspan="5">
<div class="row">
<div class="col-sm-3">
<button class="btn btn-sm btn-success" ng-click="vm.command()">Command</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-primary" ng-click="vm.sell()">Sell</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-warning" ng-click="vm.eatSome()">Eat some!</button>
</div>
<div class="col-sm-3">
<button class="btn btn-sm btn-danger" ng-click="vm.cancel()">Cancel</button>
</div>
</div>
</td>
</tr>
<tr ng-repeat="fruit in vm.bottomFruits">
<td style="background:#fcc">{{fruit.name}}</td>
<td>{{fruit.color}}</td>
<td>{{fruit.tree}}</td>
<td>{{fruit.origin}}</td>
<td>
<button class="btn btn-primary" ng-click="vm.showOptionsBottom($index)">Options</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
Here is the controller code
vm.fruits = [{
name: 'Orange',
color: 'Orange',
tree: 'Orange Tree!',
origin: 'China'
}, {
name: 'Apple',
color: 'Green',
tree: 'Apple Tree!',
origin: 'Moon'
}];
vm.topFruits = vm.fruits;
vm.bottomFruits = [];
vm.message = 'Fruit store!';
function appendTemplate(index) {
if (vm.publishShown) {
removeLastAppend();
}
vm.publishShown = true;
vm.topFruits = [];
vm.bottomFruits = [];
document.getElementById('publish-template').style.display="block";
for(i=0;i<vm.fruits.length;i++) {
if(i<=index) {
vm.topFruits[i] = vm.fruits[i];
} else {
vm.bottomFruits[i-vm.topFruits.length] = vm.fruits[i];
}
}
}
vm.showOptionsTop = function(index) {
appendTemplate(index);
}
vm.showOptionsBottom = function(index) {
appendTemplate(index+vm.topFruits.length);
}
function removeLastAppend() {
document.getElementById('publish-template').style.display="none";
vm.publishShown = false;
}
function cancel() {
removeLastAppend();
}
I am new to knockout. I am trying to use observable arrays to track the changes from UI. The UI is loading with the initial data which is stored in the array. And i am trying to add new object into the array dynamically from another screen.
Now i am able to add new object into the array. But UI is not getting reflected with new changes in the array. Below is my html and javascript code.
Am i missing something.
<html>
<head>
<link rel="stylesheet" href="bootstrap.css" type="text/css" />
<link rel="stylesheet" href="bootstrap-theme.css " type="text/css" />
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="prodconfig.css " type="text/css" />
<script src="jquery.mobile.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="cordys.min.css" type="text/css" />
<link rel="stylesheet" href="jquery.mobile.structure.min.css" type="text/css" />
<script src="knockout.js" type="text/javascript"></script>
<script src="prodconfig.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page" id="productsPage" class="dataContainer">
<div id="productDetails">
<div data-role="content" id="productTable">
<table data-role="table" class="ui-responsive table">
<thead>
<tr>
<th data-priority="6">Product Name</th>
<th data-priority="1">Description</th>
<th data-priority="2">Parent?</th>
</tr>
</thead>
<tbody id="pBody" data-bind="foreach: products">
<tr class="success">
<td><span data-bind="text: name"></span></td>
<td><span data-bind="text: desc"></span></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="prodButtons">
<button id="addProdProduct">Add Product</button>
<button id="addProdChar">Add Characteristics</button>
<button id="prodButton">Next</button>
</div>
</div>
<div id="addProductPage" data-role="page" >
<span><h3>Product Name</h3></span><input type="text" id="prodNameId"></input>
<span><h3>Product Desc</h3></span><input type="text" id="prodDescId"></input>
<span><h3>Is Parent</h3></span><input type="text" id="prodIsParentId"></input>
<button id="addProdButton">OK</button>
<div>
</body>
var configArray = new Array();
var products = [];
var services = new Array();
var chars = [];
var prd;
for(var i=0;i<2;i++){
var product = new Object();
product["name"] = "prod"+i+"Name";
product["desc"] = "prod"+i+"Desc";
product["isParent"] = "prme";
for(var j=0;j<2;j++){
var charr = new Object();
charr["name"] = "prod"+i+"char"+j;
charr["val"] = "prod"+i+"char"+j+"val";
chars[j] = charr;
}
product["chars"] = chars;
products[i] = product;
}
var ProductViewModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
$(function(){
$('#addProdProduct').click(function() {
window.location.href = "#addProductPage";
});
$('#addProdButton').click(function() {
addProduct();
});
prd = new ProductViewModel(products);
ko.applyBindings(prd);
});
function addProduct(){
var product = new Object();
product["name"] = $('#prodNameId').val();
product["desc"] = $('#prodDescId').val();
product["isParent"] = $('#prodIsParentId').val();
prd.itemToAdd(product);
prd.addItem();
window.location.href = '#';
}
You are binding to the products variable instead of to the items field on your viewmodel.
Change your binding to:
<tbody id="pBody" data-bind="foreach: items">
The code below shown a sample procedure for inserting data using knockoutjs MVVM pattern. Here i using bootstrap Modal Popup for inserting Data.
HTML
<div class="row">
<button type="button" class="btn btn-primary pull-right" data-bind="click:add" data-toggle="modal" data-target="#myModal1">
<i class="fa fa-plus"></i> Add New Data
</button>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody data-bind="template:{name:'item-view-template',foreach:products}"></tbody>
</table>
</div>
<script type="text/html" id="item-view-template">
<tr>
<td class="text-left" data-bind="text:ProductName"></td>
<br />
/tr>
</script>
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Data</h4>
</div>
<div class="modal-body" data-bind="template:{name:'item-create-template',data:selectedData}">
<div class="row">
<div class="col-md-12"></div>
</div>
</div>
</div>
</div>
</div>
<script type="text/html" id="item-create-template">
<form>
<fieldset>
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" data-bind="value:ProductName" />
</div>
<button class="btn btn-primary" data-bind="click:$parent.save">Save</button>
<button class="btn btn-default" data-dismiss="modal">Cancel</button>
</fieldset>
</form>
</script>
<script type="text/javascript">
var vm = new ProductViewModel();
ko.applyBindings(vm);
vm.init();
</script>
View Model Js File
function ProductViewModel() {
var self = {};
self.data = ko.observableArray();
self.products = ko.observableArray();
self.selectedData = ko.observable(Product({}));
self.init = function () {
$.get('/MyController/GetAll', function (data) {
$.each(data, function (key, value) {
self.products.push(Product(value));
});
});
};
self.add = function () {
self.selectedData(Product({}));
};
self.save = function() {
if (self.selectedData()) {
var jsonData = ko.toJS(self.selectedData);
$.post('/MyController/Create', jsonData, function(data) {
if (data.Status == true) {
$('#myModal1').modal('hide');
bootbox.alert("Product created successfully", function() {
self.Products.removeAll();
$.get('/MyController/GetAll', function (result) {
$.each(result.Products, function (key, value) {
self.Products.push(Product(value));
});
});
});
} else {
bootbox.alert("Duplicate values not allowed..!!");
}
});
} else {
bootbox.alert("Error!!");
}
};
return self;
}
And the Model
function Product(product) {
var self = {};
self.Id = ko.observable(product.Id || '');
self.ProductName = ko.protectedObservable(product.Name || '');
return self;
}
I think this will help you
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