Here is my HTLM Page:
<!DOCTYPE html>
<script src="Scripts/knockout-3.4.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script src="Scripts/knockout.simpleGrid.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Knockout GridView Örnek</title>
<style>
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
.ko-grid { margin-bottom: 1em; width: 25em; border: 1px solid silver; background-color:White; }
.ko-grid th { text-align:left; background-color: Black; color:White; }
.ko-grid td, th { padding: 0.4em; }
.ko-grid tr:nth-child(odd) { background-color: #DDD; }
.ko-grid-pageLinks { margin-bottom: 1em; }
.ko-grid-pageLinks a { padding: 0.5em; }
.ko-grid-pageLinks a.selected { background-color: Black; color: White; }
.liveExample { height:20em; overflow:auto }
li { list-style-type: disc; margin-left: 20px; }
</style>
</head>
<body>
<div data-bind='simpleGrid: gridViewModel'></div>
<div>Ad: </div> <input data-bind="value: Ad" /> <br />
<div>Satılan: </div> <input data-bind="value: Satis" /> <br />
<div>Fiyat: </div> <input data-bind="value: tutar" /> <br />
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: deleteFirst'>Delete first Row</button>
<button data-bind='click: deleteLast'>Delete Last Row</button>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
</body>
</html>
Here is my JavaScript:
<script type="text/javascript">
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Furious Lizard", sales: 152, price: 25.00 },
{ name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ name: "Brooding Dragon", sales: 0, price: 6350 },
{ name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var PagedGridModel = function (items) {
this.items = ko.observableArray(items);
this.sortByName = function () {
this.items.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function () {
this.gridViewModel.currentPageIndex(0);
};
this.deleteFirst = function () {
this.items.shift();
}
this.deleteLast = function () {
this.items.pop();
}
this.removeGift = function (item) {
this.initialData.remove(item);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: 4
});
this.Ad = ko.observable("");
this.Satis = ko.observable("");
this.tutar = ko.observable("");
this.addItem = function () {
if (this.Ad() != "" && this.Satis() != "" && this.tutar() != "") {
this.tutar(Number(this.tutar()));
this.Satis(Number(this.Satis()));
this.items.push({ name: this.Ad(), sales: this.Satis(), price: this.tutar() });
this.Ad("");
this.Satis("");
this.tutar("");
}
}.bind(this);
};
ko.applyBindings(new PagedGridModel(initialData));
</script>
Here is my Grid JS:
(function () {
// Private function
function getColumnsForScaffolding(data) {
if ((typeof data.length !== 'number') || data.length === 0) {
return [];
}
var columns = [];
for (var propertyName in data[0]) {
columns.push({ headerText: propertyName, rowText: propertyName });
}
return columns;
}
ko.simpleGrid = {
// Defines a view model class you can use to populate a grid
viewModel: function (configuration) {
this.data = configuration.data;
this.currentPageIndex = ko.observable(0);
this.pageSize = configuration.pageSize || 5;
// If you don't specify columns configuration, we'll use scaffolding
this.columns = configuration.columns || getColumnsForScaffolding(ko.unwrap(this.data));
this.itemsOnCurrentPage = ko.computed(function () {
var startIndex = this.pageSize * this.currentPageIndex();
return ko.unwrap(this.data).slice(startIndex, startIndex + this.pageSize);
}, this);
this.maxPageIndex = ko.computed(function () {
return Math.ceil(ko.unwrap(this.data).length / this.pageSize) - 1;
}, this);
}
};
// Templates used to render the grid
var templateEngine = new ko.nativeTemplateEngine();
templateEngine.addTemplate = function (templateName, templateMarkup) {
document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
};
templateEngine.addTemplate("ko_simpleGrid_grid", "\
<table class=\"ko-grid\" cellspacing=\"0\">\
<thead>\
<tr data-bind=\"foreach: columns\">\
<th data-bind=\"text: headerText\"></th>\
</tr>\
</thead>\
<tbody data-bind=\"foreach: itemsOnCurrentPage\">\
<tr data-bind=\"foreach: $parent.columns\">\
<td data-bind=\"text: typeof rowText == 'function' ? rowText($parent) : $parent[rowText] \"></td>\
<td>Delete</td>\
</tr>\
</tbody>\
</table>");
templateEngine.addTemplate("ko_simpleGrid_pageLinks", "\
<div class=\"ko-grid-pageLinks\">\
<span>Page:</span>\
<!-- ko foreach: ko.utils.range(0, maxPageIndex) -->\
<a href=\"#\" data-bind=\"text: $data + 1, click: function() { $root.currentPageIndex($data) }, css: { selected: $data == $root.currentPageIndex() }\">\
</a>\
<!-- /ko -->\
</div>");
// The "simpleGrid" binding
ko.bindingHandlers.simpleGrid = {
init: function () {
return { 'controlsDescendantBindings': true };
},
// This method is called to initialize the node, and will also be called again if you change what the grid is bound to
update: function (element, viewModelAccessor, allBindings) {
var viewModel = viewModelAccessor();
// Empty the element
while (element.firstChild)
ko.removeNode(element.firstChild);
// Allow the default templates to be overridden
var gridTemplateName = allBindings.get('simpleGridTemplate') || "ko_simpleGrid_grid",
pageLinksTemplateName = allBindings.get('simpleGridPagerTemplate') || "ko_simpleGrid_pageLinks";
// Render the main grid
var gridContainer = element.appendChild(document.createElement("DIV"));
ko.renderTemplate(gridTemplateName, viewModel, { templateEngine: templateEngine }, gridContainer, "replaceNode");
// Render the page links
var pageLinksContainer = element.appendChild(document.createElement("DIV"));
ko.renderTemplate(pageLinksTemplateName, viewModel, { templateEngine: templateEngine }, pageLinksContainer, "replaceNode");
}
};
})();
I want like this
But Delete not working and repeat 3 times always 1 line. I want it 1 Line 1 delete and I want to delete it. How I can do this ? I need your help guys. Thank you in advance.
Related
I have a problem
When i move a item on another slot, the item will block, and can't be moved.
Code:
$(function() {
function log(string) {
console.log(Date.now(), string);
}
function makeGrid() {
log("Make Grid...");
for (var i = 0; i < 36; i++) {
$("<div>", {
class: "slot"
}).data({
count: 0,
stackable: true
}).appendTo(".slots");
}
log("-* Grid Complete *-");
}
function makeDraggable(target) {
log("Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
$(target).draggable({
scroll: false,
helper: "clone",
cursor: "pointer",
zIndex: 27,
revert: "invalid"
});
log("After Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
}
function refreshSlot(target) {
log("Refresh Slot");
$(".size", target).html($(target).data("count"));
}
function addItem(slot, item) {
log("Add Item " + item.id);
$.extend(item, {
stackable: (item.category != 0),
count: (item.count == undefined ? 1 : item.count)
});
slot = $(slot);
var newItem = $("<div>", {
class: "item",
id: item.id,
})
.data(item)
.css("background-image", "url(" + item.img + ")");
newItem.appendTo(slot);
$("<div>", {
class: "size"
}).appendTo(slot);
slot.data({
count: item.count,
stackable: item.stackable
});
log("Item Added - Refreshing");
refreshSlot(slot);
}
function emptySlot(target) {
log("Empty Slot " + $(target).index());
$(target).data({
count: 0,
stackable: true
}).empty();
}
function loadPlayerItems(items) {
log("Loading Player Items...");
$.each(items, function(index, item) {
addItem($(".slots > .slot").eq(index), item);
});
log("-* Loading Complete *-");
}
function isAcceptable(item) {
if ($(this).children().length == 0 || $(".item", this).data("stackable")) {
return true;
}
return false;
}
var pItems = {
playerItems: [{
img: 'https://i.imgur.com/5cjSI9X.png',
name: 'bat',
id: 1,
category: 0
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 2,
category: 1
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 3,
category: 1
}
]
};
makeGrid();
loadPlayerItems(pItems.playerItems);
makeDraggable(".item");
$(".slots > .slot").droppable({
accept: isAcceptable,
drop: function(event, ui) {
var origin = ui.draggable.parent();
var target = $(this);
log("Drop Accepted; From: " + origin.index() + ", To: " + target.index());
// Increase the Count
target.data("count", target.data("count") + 1);
// Check for Stack
if (target.children().length == 0) {
addItem(target, ui.draggable.data());
} else {
refreshSlot(target);
}
// Check Orginal Stack
if (origin.data("count") > 1) {
origin.data("count", origin.data("count") - 1);
refreshSlot(origin);
} else {
emptySlot(origin);
}
makeDraggable($(".item", this));
}
});
});
body {
display: flex;
justify-content: space-between;
}
#inventory {
width: 100vw;
height: 56.25vw;
background: rgba(0,0,0,.5);
}
.list-slots {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,.7);
width: 41.667vw;
height: 41.667vw;
max-width: 80%;
}
.slots {
max-width: 87%;
margin: auto;
padding-top: 3.125vw;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.slots .slot {
width: 100px;
height: calc(100px + 1em);
background-color: #ccc;
margin-bottom: 0.781vw;
}
.slots .slot .item {
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="inventory">
<div class="list-slots">
<div class="slots"></div>
</div>
</div>
I am trying to build a grid component in vue. And then use this to set up a sortable and searchable chart. I need to use Single File Component. I also used vue-router. Here in below are my two .vue files. I can only see the search bar in my localhost. And there are several errors showed up in the console. The original Fiddle of separate files https://jsfiddle.net/Tertia/vbyon64p/6/?utm_source=website&utm_medium=embed&utm_campaign=vbyon64p
This is my chart.vue
<template>
<div id="demo">
<form id="search">
Search <input name="query" v-model="searchQuery">
</form>
<demo-grid></demo-grid>
</div>
</template>
<script>
import DemoGrid from "./grid";
export default {
name :'chart',
components: {DemoGrid},
props: {
heroes: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {}
this.columns.forEach(function (key) {
sortOrders[key] = 1
})
return {
sortKey: '',
sortOrders: sortOrders,
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
]
}
},
computed: {
filteredHeroes: function () {
var sortKey = this.sortKey
var filterKey = this.filterKey && this.filterKey.toLowerCase()
var order = this.sortOrders[sortKey] || 1
var heroes = this.heroes
if (filterKey) {
heroes = heroes.filter(function (row) {
return Object.keys(row).some(function (key) {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1
})
})
}
if (sortKey) {
heroes = heroes.slice().sort(function (a, b) {
a = a[sortKey]
b = b[sortKey]
return (a === b ? 0 : a > b ? 1 : -1) * order
})
}
return heroes
}
},
filters: {
capitalize: function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
}
</script>
<style >
This is my grid.vue, a template
<table>
<thead>
<tr>
<th v-for="key in columns"
#click="sortBy(key)"
:class="{ active: sortKey == key }">
{{ key | capitalize }}
<span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="entry in filteredHeroes">
<td v-for="key in columns">
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
Here is the ideal look of the grid. It is sortable and searchable.
And here are my errors.
You've got your code in all the wrong places. Most likely due to the lack of understanding of the Single File Components concept and Component Basics.
Here's me literally copy and pasting code from the original fiddle into their respective components.
Your chart.vue should look like this:
<template>
<div id="demo">
<form id="search">
Search
<input name="query" v-model="searchQuery">
</form>
<demo-grid :heroes="gridData" :columns="gridColumns" :filter-key="searchQuery"></demo-grid>
</div>
</template>
<script>
import DemoGrid from "./grid.vue";
export default {
name: "Chart",
components: {
DemoGrid
},
data() {
return {
searchQuery: "",
gridColumns: ["name", "power"],
gridData: [
{ name: "Chuck Norris", power: Infinity },
{ name: "Bruce Lee", power: 9000 },
{ name: "Jackie Chan", power: 7000 },
{ name: "Jet Li", power: 8000 }
]
};
}
};
</script>
Your grid.vue should look like this:
<template>
<table>
<thead>
<tr>
<th
v-for="(key, index) in columns"
:key="index"
:class="{ active: sortKey == key }"
#click="sortBy(key)"
>
{{ key | capitalize }}
<span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'"></span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(entry, index) in filteredHeroes" :key="index">
<td v-for="(key, index) in columns" :key="index">{{ entry[key] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
name: "DemoGrid",
props: {
heroes: Array,
columns: Array,
filterKey: String
},
data: function() {
const sortOrders = {};
this.columns.forEach(function(key) {
sortOrders[key] = 1;
});
return {
sortKey: "",
sortOrders: sortOrders
};
},
computed: {
filteredHeroes() {
const sortKey = this.sortKey;
const filterKey = this.filterKey && this.filterKey.toLowerCase();
const order = this.sortOrders[sortKey] || 1;
let heroes = this.heroes;
if (filterKey) {
heroes = heroes.filter(function(row) {
return Object.keys(row).some(function(key) {
return (
String(row[key])
.toLowerCase()
.indexOf(filterKey) > -1
);
});
});
}
if (sortKey) {
heroes = heroes.slice().sort(function(a, b) {
a = a[sortKey];
b = b[sortKey];
return (a === b ? 0 : a > b ? 1 : -1) * order;
});
}
return heroes;
}
},
filters: {
capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
},
methods: {
sortBy(key) {
this.sortKey = key;
this.sortOrders[key] = this.sortOrders[key] * -1;
}
}
};
</script>
<style scoped>
table {
border: 2px solid #42b983;
border-radius: 3px;
background-color: #fff;
}
th {
background-color: #42b983;
color: rgba(255, 255, 255, 0.66);
cursor: pointer;
user-select: none;
}
td {
background-color: #f9f9f9;
}
th,
td {
min-width: 120px;
padding: 10px 20px;
}
th.active {
color: #fff;
}
th.active .arrow {
opacity: 1;
}
.arrow {
display: inline-block;
vertical-align: middle;
width: 0;
height: 0;
margin-left: 5px;
opacity: 0.66;
}
.arrow.asc {
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-bottom: 4px solid #fff;
}
.arrow.dsc {
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid #fff;
}
</style>
Assuming both components are in the same directory.
I'm trying to build a carousel in JS that uses an array to store my data.
I want my box on the left to show the value for "Client" and the box on the right to show the value for "Candidate".
I can't seem to get it working despite what I believe is all correct?
let testimonials = [{
client: "Raphel",
candidate: "male"
},
{
client: "Tom",
candidate: "male"
},
{
client: "Jerry",
candidate: "male"
},
{
client: "Dorry",
candidate: "female"
}
];
var i = 0;
function nextItem() {
i = i + 1;
i = i % testimonials.length;
return testimonials[i].candidate;
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
return testimonials[i].client;
}
window.addEventListener('load', function() {
$('.client-box').html(testimonials[i].client);
$('.candidate-box').html(testimonials[i].candidate);
$('.left-btn').on('click', function(e) {
$('.client-box').html(prevItem());
$('.candidate-box').html(prevItem());
});
$('.right-btn').on('click', function(e) {
$('.client-box').html(nextItem());
$('.candidate-box').html(nextItem());
});
});
https://jsfiddle.net/cL5mok3f/
Fixing the code:
let testimonials = [{
client: "Raphel",
candidate: "male"
},
{
client: "Tom",
candidate: "male"
},
{
client: "Jerry",
candidate: "male"
},
{
client: "Dorry",
candidate: "female"
}
];
var i = 0;
function nextItem() {
i = i + 1;
i = i % testimonials.length;
return testimonials[i];
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
return testimonials[i];
}
window.addEventListener('load', function() {
$('.client-box').html(testimonials[i].client);
$('.candidate-box').html(testimonials[i].candidate);
$('.left-btn').on('click', function(e) {
var prev = prevItem();
$('.client-box').html(prev.client);
$('.candidate-box').html(prev.candidate);
});
$('.right-btn').on('click', function(e) {
var next = nextItem();
$('.client-box').html(next.client);
$('.candidate-box').html(next.candidate);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="client-box"></div>
<div class="candidate-box"></div>
<input type="button" class="left-btn" value="Prev" />
<input type="button" class="right-btn" value="Next" />
To achieve expected result, use below option
Issue: PrevItem and nextItem methods are called twice on clicking left and right which creates inconsistent carousel
Code sample
let testimonials = [
{client: "Raphel", candidate: "male"},
{client: "Tom", candidate: "male"},
{client: "Jerry", candidate: "male"},
{client: "Dorry", candidate: "female"}
];
var i = 0;
$('.client-box').text(testimonials[0].client);
$('.candidate-box').text(testimonials[1].candidate);
function nextItem() {
i = i + 1;
if (i === testimonials.length) {
i = i % testimonials.length;
}
return testimonials[i];
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
console.log("prev", i)
return testimonials[i];
}
$('.left-btn').on('click', function(e){
let val = prevItem()
$('.client-box').text(val.client);
$('.candidate-box').text(val.candidate);
});
$('.right-btn').on('click', function(e){
let val = nextItem()
$('.client-box').text(val.client);
$('.candidate-box').text(val.candidate);
});
.testimonial-carousel {
position: relative;
width: 1000px;
}
.testimonial-carousel::after {
content: "";
display: block;
clear: both;
}
.testimonial-carousel .testimonial-box {
width: 500px;
height: 100px;
float: left;
background: #999999;
}
.testimonial-carousel .testimonial-box.candidate-box {
background: white;
margin-top: 2rem;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
}
.testimonial-carousel .buttons {
position: absolute;
bottom: -60px;
right: 20px;
}
.testimonial-carousel .buttons::after {
content: "";
display: block;
clear: both;
}
.testimonial-carousel .buttons .btn {
background: black;
width: 60px;
height: 60px;
float: left;
margin-right: 5px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testimonial-carousel">
<div class="testimonial-box client-box"></div>
<div class="testimonial-box candidate-box"></div>
<div class="buttons">
LEFT
RIGHT
</div>
</div>
codepen - https://codepen.io/nagasai/pen/wLKoVv
In my example jsfidle you can see my doubt.
My jsfiddle
How do I get it to count the number of it and only appears to me once and not repeatedly.
My Html:
<section class="left" style="border-right:1px">
<div class="filter">
Pant Size
<div>
<div ng-repeat="professionalarea in pantsGroup">
<b><input type="checkbox" ng-model="usePants[professionalarea.description]"/>{{professionalarea.description}}</b>
<span>({{(filteredPlayers | filter:professionalarea).length}})</span>
</div>
</div>
</div>
</section>
My controller
$scope.$watch(function () {
return {
players: $scope.players,
usePants: $scope.usePants
}
}, function (value) {
var selected;
//here i want call professionalarea.description and don't pants
$scope.pantsGroup = uniqueItems($scope.players, 'professionalarea');
var filterAfterPants = [];
selected = false;
for (var j in $scope.players) {
var p = $scope.players[j];
for (var i in $scope.usePants) {
if ($scope.usePants[i]) {
selected = true;
if (i == p.professionalarea.description) {
filterAfterPants.push(p);
break;
}
}
}
}
if (!selected) {
filterAfterPants = $scope.players;
}
$scope.filteredPlayers = filterAfterPants;
}, true);
Example Image
Image
Added new function to get distinct items i.e. getDistinctValue
Please find following snippet..
(function () {
'use strict';
var myApp = angular.module('myApp', []);
var uniqueItems = function (data, key) {
var result = new Array();
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
console.log(value);
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
function getDistinctValue(items) {
var lookup = {};
var result = [];
for (var item, i = 0; item = items[i++];) {
var name = item.professionalarea.description;
if (!(name in lookup)) {
lookup[name] = 1;
result.push(name);
}
}
return result;
}
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
}]);
myApp.controller('myCtrl', ['$scope', function ($scope) {
$scope.usePants = {};
$scope.players = [
{
name: 'Bruce Wayne',
shirt: 'XXL',
pants: '42',
professionalarea: {
idAreaProfissional: 1,
description: "IT"
},
shoes: '12'
}, {
name: 'Bruce Wayne',
shirt: 'XXL',
pants: '28',
professionalarea: {
idAreaProfissional: 1,
description: "test"
},
shoes: '12'
}, {
name: 'Bruce Wayne',
shirt: 'XXL',
pants: '35',
professionalarea: {
idAreaProfissional: 1,
description: "IT"
},
shoes: '12'
}
];
// Watch the pants that are selected
$scope.$watch(function () {
return {
players: $scope.players,
usePants: $scope.usePants
}
}, function (value) {
var selected;
//here i want call professionalarea.description and don't pants
$scope.pantsGroup = getDistinctValue($scope.players);
var filterAfterPants = [];
selected = false;
for (var j in $scope.players) {
var p = $scope.players[j];
for (var i in $scope.usePants) {
if ($scope.usePants[i]) {
selected = true;
if (i == p.professionalarea.description) {
filterAfterPants.push(p);
break;
}
}
}
}
if (!selected) {
filterAfterPants = $scope.players;
}
$scope.filteredPlayers = filterAfterPants;
}, true);
$scope.$watch('filtered', function (newValue) {
if (angular.isArray(newValue)) {
console.log(newValue.length);
}
}, true);
}]);
myApp.filter('groupBy',
function () {
return function (collection, key) {
if (collection === null) return;
return uniqueItems(collection, key);
};
});
})();
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="app.js" type="text/javascript"></script>
<style>
.gridStyle {
border: 1px solid rgb(212, 212, 212);
margin-left: 15px;
width: 97%;
height: 130px;
float: left;
font-weight: normal;
padding: 35px 10px 10px 10px;
}
</style>
<title>Upload </title>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<div>
<section class="left" style="border-right:1px">
<div class="filter">
Pant Size
<div>
<div ng-repeat="professionalarea in pantsGroup">
<b><input type="checkbox" ng-model="usePants[professionalarea]" />{{professionalarea}}</b>
<span>({{filteredPlayers.length}})</span>
</div>
</div>
</div>
</section>
<section class="right" style="border-right:1px">
<div>
<ul>
<li ng-repeat="player in filteredPlayers | filter:query">
<p><b>Player: {{player.name}}</b></p>
<p>Shirt Size: {{player.shirt}} Pant Size: {{player.pants}} Shoe Size: {{player.shoes}}</p>
</li>
</ul>
</div>
</section>
</div>
</div>
</body>
</html>
Now, I have tow buttons. The first button named "array1", the other button named 'array2'. I have an array called "newArray." I have an array named "array1". I have an array named "array2".I have an array called "unselectedArray."
When I click the array1 button, I want to show the item in array1, but the item is not in "newArray1". When I click the array2 button, I want to show the item in array2, but the item is not in "newArray1" This show array is "unselectedArray."
When I click the item in the "unselectedArray," the item is added in 'newArrray';
I use two hours to solve it, but I haven't written the right code.
This is my code:
<style>
.bigDiv {
width: 500px; height: 100%;
margin: 60px auto; background-color: red;
}
li {
float: left;
width: 50px; height: 50px;
}
.selected,.buttonArea,.unselected {
height: 100px;
}
</style>
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-repeat="item in newArray">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray">
{{item.text}}
</li>
</ul>
</div>
</div>
angular.module('myApp', []).controller('con', function ($scope) {
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
};
$scope.showArrayFun = function (arrayName) {
if (arrayName == 'array1') {
$scope.unselectedArray = $scope.array1.filter(function (item) {
console.log(($scope.newArray.indexOf(item) == -1));
return ( ($scope.newArray.indexOf(item) == -1) == true );
});
} else if (arrayName == 'array2') {
$scope.unselectedArray = $scope.array2.filter(function (item) {
console.log(($scope.newArray.indexOf(item) == -1));
return ( ($scope.newArray.indexOf(item) == -1) == true );
});
}
}
}
);
Why my code not work? Who can correct my code?
Please write the code which is using $filter.
Who can create AngularJS custom filters to realize it.
// Code goes here
angular.module('myApp', []).controller('con', function ($scope) {
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
$scope.unselectedArray.splice(index, 1);
};
$scope.showArrayFun = function (arrayName) {
if (arrayName == 'array1') {
$scope.unselectedArray = $scope.array1.filter(function (item) {
return ( ($scope.newArray.indexOf(item) == -1));
});
} else if (arrayName == 'array2') {
$scope.unselectedArray = $scope.array2.filter(function (item) {
return ( ($scope.newArray.indexOf(item) == -1));
});
}
};
})
/* Styles go here */
.bigDiv {
width: 500px; height: 100%;
margin: 60px auto;
background-color: red;
}
li {
float: left;
width: 50px; height: 50px;
}
.selected,.buttonArea,.unselected {
height: 100px;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="con">
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-repeat="item in newArray">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray">
{{item.text}}
</li>
</ul>
</div>
</div>
</body>
</html>
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-click=" deleteItemFun($index)" ng-repeat="item in newArray track by $index ">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray | fiArray : newArray ">
{{item.text}}
</li>
</ul>
</div>
</div>
angular.module('myApp', []).filter('fiArray', function () {
return function (array, aimArray) {
var tempArray = array;
if (tempArray.length == 0)
return [];
for (var i = 0; i < aimArray.length; i++) {
for (var j = 0; j < tempArray.length; j++) {
if (tempArray[j].id === aimArray[i].id) {
tempArray.splice(j, 1);
j--;
break;
}
}
}
return tempArray;
}
})
.controller('con', ['$scope', 'fiArrayFilter', function ($scope, fiArrayFilter) {
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
};
$scope.deleteItemFun = function (index) {
$scope.newArray.splice(index, 1)
}
$scope.showArrayFun = function (arrayName) {
var copyArr = [];
if (arrayName == 'array1') {
copyArr = $scope.array1.concat();
}
else if (arrayName == 'array2') {
copyArr = $scope.array2.concat();
}
$scope.unselectedArray = copyArr;
}
}])
;