I have an array of items in form of service - as I know it's like proper way to keep data you use in different controllers.I watched tutorial and did the filtering by brands. But I have an obstacle with filtering of my Items by another parameters, such as price, length and frequency... So I have made sliders by another example but I have no idea how to tie up it with my array of Items. Please do me a favour, show how to tie up even one of my parameters, price for example.
http://angular.zxcvbn.ru
services.js:
myApp.service('ProductDataService', function() {
//sample data
var items = [
{ name:'Picachoo', id:1, price:25000, pict:'http://www.metrord.do/_internal/gxml!0/2qijkhn0ctpwx8acoz5fxkpvtmr4nbh$r05jcw5nnz5dt1u7odn7q01jm5k3ezo/screen-shot-2016-07-24-at-11-55-41-am.jpeg', len: 250, friq: 5000, brand: 'came' },
{ name:'Tortule', id:2, price:30000, pict:'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcR2APj6_uBfhHRXLn1dZN58ZocpzMxGMFLZmuqHEU5SybKN4QAVfg', len: 250, friq: 300, brand: 'came' },
{ name:'Dragon', id:3, price:33500, pict:'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSJotIxkjgXgm9m3m-0FuUxN6g9fGGXmP84VDRrPZoWa-x8Dqqd', len: 350, friq: 300, brand: 'came' },
{ name:'encrypted1', id:4, price:45000, pict:'http://gaidi.ru/wp-content/uploads/2016/07/kak-pravilno-lovit-pokemonov-v-pokemon-go.jpg', len: 400, friq: 3000, brand: 'came' },
{ name:'pravilno', id:5, price:48600, pict:'http://vignette3.wikia.nocookie.net/pokemon/images/2/2e/009Blastoise_Dream.png/revision/latest?cb=20140812050618', len: 550, friq: 2000, brand: 'came' },
{ name:'images', id:6, price:30000, pict:'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSqywi0lMtmf1sAR-20rg0HXETMueY3H71iJP35WsdsPHGVokK41g', len: 550, friq: 1000, brand: 'bft' },
{ name:'Foxy', id:7, price:38000, pict:'http://vgtimes.ru/uploads/posts/2016-07/1468938437_pk_vulpix.png', len: 350, friq: 10000, brand: 'bft' },
{ name:'Pteradactys', id:8, price:43000, pict:'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRJBXypwhl8-z4IsAZokgQlqPx_vZymtENBdlPy1HhN34uODEZ5', len: 800, friq: 10000, brand: 'bft' },
{ name:'encrypted', id:9, price:35800, pict:'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQZNKoA9LMtQHhgU4Toy7xXfzGEp6Rb4Kv6I16RgMjWO0Dnb36EFA', len: 1200, friq: 3000, brand: 'faac' },
{ name:'Jidjfj', id:10, price:14000, pict:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRPBKrRLvhYm9y-LxwRM4Qc_psMjd_luij_04ChmmQjcrdxgmcG3w', len: 800, friq: 5000, brand: 'fors' }
];
brands = {came : true, bft : true, faac : true, fors : true} ;
this.getItems = function() {
return items;
};
this.getBrands = function() {
return brands;
};
this.maxPrice = function() {
var max;
var producto;
for(var i = 0; i < items.length-1; i++) {
for(var j = 0; j < items.length-i-1; j++){
if (producto[j] > producto[j+1]) {
max = producto[j];
producto[j] = producto[j+1];
producto[j+1] = b;
}
}
}
return max;
}
this.minPrice = function() {
var min;
var producto;
for(var i = 0; i < items.length-1; i++) {
for(var j = 0; j < items.length-i-1; j++){
if (producto[j] < producto[j+1]) {
min = producto[j];
producto[j] = producto[j+1];
producto[j+1] = b;
}
}
}
return min;
}
});
slider_price.js:
myApp.controller('priceCtrl', function($scope, ProductDataService) {
$scope.search = { price_min : '', price_max : '', amount_min : 14000, amount_max : 48600 };
});
/* Range Slider
Input with default values:
-min=0 // Min slider value
-max=100 // Max slider value
-step=1 // Steps
Output / Input model
-value-min // Default value #min
-value-max // Default value #max
example:
<slider-range min="0" max="100" step="5" value-min="scope.form.slider_value_min" value-max="scope.form.slider_value_max"></slider-range>
*/
myApp.directive('priceRange', ['$document',function($document) {
// Move slider handle and range line
var moveHandle = function(handle, elem, posX) {
$(elem).find('.handle.'+handle).css("left",posX +'%');
};
var moveRange = function(elem,posMin,posMax) {
$(elem).find('.range').css("left",posMin +'%');
$(elem).find('.range').css("width",posMax - posMin +'%');
};
return {
template: '<div class="slider horizontal">'+
'<div class="range"></div>'+
'<a class="handle min" ng-mousedown="mouseDownMin($event)"></a>'+
'<a class="handle max" ng-mousedown="mouseDownMax($event)"></a>'+
'</div>',
replace: true,
restrict: 'E',
scope:{
valueMin:"=",
valueMax:"="
},
link: function postLink(scope, element, attrs) {
// Initilization
var dragging = false;
var startPointXMin = 0;
var startPointXMax = 0;
var xPosMin = 0;
var xPosMax = 0;
var settings = {
"min" : (typeof(attrs.min) !== "undefined" ? parseInt(attrs.min,10) : 0),
"max" : (typeof(attrs.max) !== "undefined" ? parseInt(attrs.max,10) : 100),
"step" : (typeof(attrs.step) !== "undefined" ? parseInt(attrs.step,10) : 1)
};
if ( typeof(scope.valueMin) == "undefined" || scope.valueMin === '' )
scope.valueMin = settings.min;
if ( typeof(scope.valueMax) == "undefined" || scope.valueMax === '' )
scope.valueMax = settings.max;
// Track changes only from the outside of the directive
scope.$watch('valueMin', function() {
if (dragging) return;
xPosMin = ( scope.valueMin - settings.min ) / (settings.max - settings.min ) * 100;
if(xPosMin < 0) {
xPosMin = 0;
} else if(xPosMin > 100) {
xPosMin = 100;
}
moveHandle("min",element,xPosMin);
moveRange(element,xPosMin,xPosMax);
});
scope.$watch('valueMax', function() {
if (dragging) return;
xPosMax = ( scope.valueMax - settings.min ) / (settings.max - settings.min ) * 100;
if(xPosMax < 0) {
xPosMax = 0;
} else if(xPosMax > 100) {
xPosMax = 100;
}
moveHandle("max",element,xPosMax);
moveRange(element,xPosMin,xPosMax);
});
// Real action control is here
scope.mouseDownMin = function($event) {
dragging = true;
startPointXMin = $event.pageX;
// Bind to full document, to make move easiery (not to lose focus on y axis)
$document.on('mousemove', function($event) {
if(!dragging) return;
//Calculate handle position
var moveDelta = $event.pageX - startPointXMin;
xPosMin = xPosMin + ( (moveDelta / element.outerWidth()) * 100 );
if(xPosMin < 0) {
xPosMin = 0;
} else if(xPosMin > xPosMax) {
xPosMin = xPosMax;
} else {
// Prevent generating "lag" if moving outside window
startPointXMin = $event.pageX;
}
scope.valueMin = Math.round((((settings.max - settings.min ) * (xPosMin / 100))+settings.min)/settings.step ) * settings.step;
scope.$apply();
// Move the Handle
moveHandle("min", element,xPosMin);
moveRange(element,xPosMin,xPosMax);
});
$document.mouseup(function(){
dragging = false;
$document.unbind('mousemove');
$document.unbind('mousemove');
});
};
scope.mouseDownMax = function($event) {
dragging = true;
startPointXMax = $event.pageX;
// Bind to full document, to make move easiery (not to lose focus on y axis)
$document.on('mousemove', function($event) {
if(!dragging) return;
//Calculate handle position
var moveDelta = $event.pageX - startPointXMax;
xPosMax = xPosMax + ( (moveDelta / element.outerWidth()) * 100 );
if(xPosMax > 100) {
xPosMax = 100;
} else if(xPosMax < xPosMin) {
xPosMax = xPosMin;
} else {
// Prevent generating "lag" if moving outside window
startPointXMax = $event.pageX;
}
scope.valueMax = Math.round((((settings.max - settings.min ) * (xPosMax / 100))+settings.min)/settings.step ) * settings.step;
scope.$apply();
// Move the Handle
moveHandle("max", element,xPosMax);
moveRange(element,xPosMin,xPosMax);
});
$document.mouseup(function(){
dragging = false;
$document.unbind('mousemove');
$document.unbind('mousemove');
});
};
}
};
}]);
app.js:
var myApp = angular.module("filterApp", []);
myApp.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
$window.alert(greeting);
};
}]);
myApp.controller('coolCtrl', function($scope) {
$scope.whoAmI = function(){
console.log("This is whoAmI function in the coolCtrl!");
};
});
myApp.controller('mainCtrl', function($scope, ProductDataService){
$scope.helloWorld = function(){
console.log("This is helloWorld function in the mailCtrl!");
};
$scope.items = ProductDataService.getItems();
$scope.brands = ProductDataService.getBrands();
$scope.refresh = function(){
location.reload();
};
$scope.showPopUpMsg = false;
$scope.openPopUp = function( text ) {
$scope.showPopUpMsg = true;
$scope.popUpMsgContent = text;
$scope.minimun = 123;
};
});
jilters.js:
myApp.filter('brandsfilter', function () {
return function(input, filter) {
var result = [];
angular.forEach(input, function (item) {
angular.forEach(filter, function (isfiltered, brand) {
if (isfiltered && brand === item.brand) {
result.push(item);
}
});
});
return result;
};
});
index.php:
<?php
require 'scripts/mail_script.php';
?>
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="styles/normalize.css">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="styles/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- for slider work -->
</head>
<body ng-app="filterApp" ng-controller='mainCtrl'>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container">
<section class='top' >
<h1>Filter</h1>
<!-- //// http://embed.plnkr.co/woqn3i/ /// -->
<!-- ///////// -->
<div class="row" id='items'>
<div>
<div class="col-md-4" ><h2>params:</h2>
<div ng-controller="priceCtrl">
<p>Choose price:</p>
<p>min: <input type="number" ng-model="search.amount_min"/> $</p>
<p>max: <input type="number" ng-model="search.amount_max"/> $</p>
<slider-range min="14000" max="48600" step="100" value-min="search.amount_min" value-max="search.amount_max"></slider-range>
</div>
<hr>
<p>По названию:</p>
<p><input type="text" ng-model="price" /></p>
<p>Brand:</p>
<ul >
<li ng-repeat="(brand, value) in brands">
<input type="checkbox" ng-model="brands[brand]" /> {{brand}}
</li>
</ul>
<hr>
<!-- //// http://embed.plnkr.co/woqn3i/ /// -->
<div ng-controller="filterCtrl">
<p>length:</p>
<p>От: <input type="text" ng-model="search.price_min"/> meters</p>
<p>До: <input type="text" ng-model="search.price_max"/> meters</p>
<slider-range min="2.5" max="12" value-min="search.price_min" value-max="search.price_max"></slider-range>
<hr>
<p>friquincy:</p>
<p>Min: <input type="number" ng-model="search.amount_min"/> times</p>
<p>Max: <input type="number" ng-model="search.amount_max"/> times</p>
<slider-range min="300" max="10000" step="100" value-min="search.amount_min" value-max="search.amount_max"></slider-range>
</div>
<hr>
<!-- ///////// -->
<div class="actions"/>
<input type="button" value="Сбросить" ng-click='refresh()'>
</div>
</div>
<div class="col-md-8"><h2>______ kinds</h2>
<?php
if($success) echo '<h4 class="bg-success text-center">'.'Сообщение отправлено!' . '</h4>';
if($error_message) echo '<h4 class="bg-danger text-center">'.'Сообщение не отправлено:' . $error_message. '</h4>';
?>
<div class="row">
<!-- LOOP.-->
<div ng-repeat="item in items | filter:price | orderBy:price | brandsfilter:brands ">
<div class="col-md-4 col-sm-6 col-sx-12">
<div class="item-inner">
<div class="image-product">
<div class="caption">
<div class="box-view">
<div class="name">{{item.name}}</div>
</div>
</div>
<img src="{{item.pict}}" alt="{{item.name}}" title="{{item.name}}" class="img-responsive">
<p class="price"><span class="price">Price: {{item.price}} $.</span></p>
<p class="description">{{item.name}} - just another piece of information, first preporty is {{item.len}} m. <br>another is: {{item.friq}} per day. </p>
</div>
</div>
</div><!-- col -->
</div> <!-- ng-repeat -->
</div> <!-- row -->
</div>
</div> <!-- mainCtrl -->
</section>
</div>
<div class="panel-footer">
<script src="vendor/angular.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/services.js"></script>
<script src="scripts/filters.js"></script>
<script src="scripts/slider.js"></script>
<script src="scripts/slider_price.js"></script>
<script src="vendor/jquery.js"></script>
<script src="vendor/bootstrap.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
</div>
</body>
</html>
AngularJS built-in filter which you already used supports multiple keywords filter see, you only need to implement comparator function to fulfill your needs.
First, change your filter in template to
<div ng-repeat="item in items | filter:myFilters:myComparator | orderBy:price">
then inside your filterCtrl you need to define myFilters and myComparator
$scope.myFilters = {price: 4000, brand: 'abc'};
$scope.myComparator = function(actual, expected) {
if (actual == parseInt(actual)) {
return actual > expected;
}
else {
return actual == expected;
}
}
Inside myComparator you can customise how you want to filter it (exact match, arithmetic comparison or partial match, just remember to return Boolean.
Just update $scope.myFilters whenever your filter keywords changed, the result will be updated in next digest cycle.
Related
I am trying to calculate the sum of a dynamic div for different categories, and then place that value in a div. What I don't understand, is how to figure out the total based on different categories. Here is a screencast of what I am talking about https://www.screencast.com/t/js8LBNfXo9sa. Here is also a link to my code pen which houses my code https://codepen.io/nfinsand/project/full/ZLNEon/.
var addListItem = document.getElementById("add-more");
addListItem.addEventListener("click", function() {
createNewItem();
});
//Display Month and Day
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
today = mm + "/" + dd;
document.getElementById("current-date").innerHTML = today;
//Creates new elements
function createNewItem() {
var u = document.getElementById("full-item-list");
var l = document.createElement("li");
var elinput = document.createElement('input');
var expenseName = document.createElement('input');
var icon = document.createElement('img');
var optionsArray = [{
'itemText': 'Category',
'itemDisabled': true,
'itemSelected': true
},
'Auto & Transport',
'Health & Fitness',
'Home',
'Personal Care',
'Pets',
'Shopping',
'Entertainment',
'Investments'
];
var selectElem = document.createElement('select');
selectElem.setAttribute('name', 'selectThis');
// iterate through the array of options
optionsArray.forEach(function(item) {
var text = (typeof(item) === 'string') ? item : item.itemText;
var option = document.createElement('option');
var optionText = document.createTextNode(text);
option.appendChild(optionText);
if (typeof(item) === 'object') {
// handle custom attributes
Object.keys(item).forEach(function(key) {
switch (key) {
case 'itemDisabled':
if (item[key]) {
option.setAttribute('disabled', true);
}
break;
case 'itemSelected':
if (item[key]) {
option.setAttribute('selected', true);
}
break;
default:
break;
}
});
}
selectElem.appendChild(option);
});
expenseName.setAttribute('type', 'text');
expenseName.setAttribute('placeholder', 'Expense name');
expenseName.setAttribute('class', 'expense-input-name')
expenseName.setAttribute('name', 'totalExpense');
elinput.setAttribute('type', 'number');
elinput.setAttribute('class', 'li-input');
elinput.setAttribute('placeholder', 'Enter amount');
elinput.setAttribute('name', 'qty');
l.setAttribute('class', 'list-item');
l.setAttribute('name', 'li-name');
icon.setAttribute('class', 'remove-icon');
icon.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/375261/System_Delete.ico');
icon.setAttribute("id", "icon-id");
icon.addEventListener('click', function(e) {
thaticon(e);
}, false);
l.appendChild(selectElem);
l.appendChild(expenseName);
l.appendChild(elinput);
l.appendChild(icon);
u.appendChild(l);
}
//Deletes elements
function thaticon(e) {
console.log("test");
var el = e.target;
var elListItem = el.parentNode;
elFullList = elListItem.parentNode;
elFullList.removeChild(elListItem);
}
//Calculates and displays results
function displayResult() {
var arr = document.getElementsByName("qty");
var wage = document.getElementById("inputWage").value;
var jumboDiv = document.getElementById("jumbo-results").style.display = "block";
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseFloat(arr[i].value)) tot += parseFloat(arr[i].value);
}
document.getElementById("result").innerHTML = "Total Expenses: $" + tot.toFixed(2);
document.getElementById("left").innerHTML = "Left Over: $" + ((wage - tot).toFixed(2));
}
//Resets and clears entire entry
function resetForm() {
var jumboDiv = document.getElementById("jumbo-results").style.display = "none";
document.getElementById("full-item-list").innerHTML = "";
document.getElementById("inputWage").value = "";
document.getElementById("result").innerHTML = "";
document.getElementById("left").innerHTML = "";
document.getElementById("number-display").innerHTML = "";
}
//Displays the selected categories by user with the total sum for each one
function displayCategory() {
}
//Capture screen shots
/*function captureScreen() {
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
}*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Expense Tracker</title>
<link rel="stylesheet" href="css/style.css">
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Raleway:300" rel="stylesheet">
</head>
<body>
<div id="capture" class="container-fluid">
<div class="centerDiv">
<p class="mainHeading">Expense Calculator</p>
<p id="current-date"></p>
<div class="jumbotron jumbo2">
<h4>Categories</h4>
<div id="category-display"><br>
<div class="flex-container">
<div id="color-1"></div>
<div class="categoryItem">Auto & Transport</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-2"></div>
<div class="categoryItem">Health & Fitness</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-3"></div>
<div class="categoryItem">Home</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-4"></div>
<div class="categoryItem">Personal Care</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-5"></div>
<div class="categoryItem">Pets</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-6"></div>
<div class="categoryItem">Shopping</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-7"></div>
<div class="categoryItem">Entertainment</div>
<div class="well">$0.00</div>
</div>
<div class="flex-container">
<div id="color-8"></div>
<div class="categoryItem">Investments</div>
<div class="well">$0.00</div>
</div>
</div>
</div>
<div class="jumbotron">
<label class="expenseLabel">Income:</label><br>
<input id="inputWage" type="number" placeholder="Paycheck Amount"><br><br><br>
<label>Expenses:</label>
<ul id="full-item-list"></ul>
<div class="listItem">
<button id="add-more" class='btn btn-warning addExpenseBtn'>Add Expense</button>
<button class="btn btn-warning submitExpenseBtn" type="button" onclick="displayResult(); displayCategory()">Submit</button>
<button class="btn btn-warning resetExpenseBtn" type="button" onclick="resetForm()">Reset</button>
</div>
</div>
<div id="jumbo-results" class="jumbotron">
<p id="result"></p><br>
<p id="left"></p>
</div>
<button class="btn btn-warning captureBtn" onclick="captureScreen()">Save Me</button>
</div>
</div>
<footer>
<small>© Copyright 2018, Noble Finsand</small>
</footer>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js'></script>
<script src="js/index.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/html2canvas.min.js"></script>
</body>
</html>
In order to calculate the total based on the categories, you will need to create a list of objects that have all the data the user entered.
From a code hygiene perspective creating the list and performing calculations on it should be separate tasks.
Similar to how you are looping through all the qty fields entered by the user in displayResult you can build out your list of expenses and then process that final result. Handling validation of each part will be challenging as they are all different fields and not guaranteed to have valid data.
Something like Angular can make this a lot easier as the hard part of binding input fields to a model is taken care of for you.
Regardless of how you create the list calculating the total by category is simple.
Assuming you create a list like this
var myExpenses = [
{'category': 'Home', name: 'rent', 'amount': 500},
{'category': 'Pets', name: 'cat food', 'amount': 45},
{'category': 'Home', name: 'utilities', 'amount': 200},
{'category': 'Pets', name: 'vet', 'amount': 42},
{'category': 'Home', name: 'trash', 'amount': 50},
{'category': 'Entertainment', name: 'date night', 'amount': 80}
];
Then these functions will be able to return you the grand total of all the expenses and each expense based on your categories.
function totalExpenses (expenses) {
return expenses.reduce(function (total, expense) {
return total + expense.amount;
}, 0);
}
function totalExpenseByCategory(categories, expenses) {
var categorizedExpenses = [];
categories.map(function (category) {
var currentExpenses = expenses.filter(function (expense) {
return expense.category === category;
});
var total = totalExpenses(currentExpenses);
categorizedExpenses.push({'category': category, 'amount': total})
});
return categorizedExpenses;
}
These functions use Filter, Map and Reduce on arrays to calculate the totals. You can learn more about them here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
I have a list and when I click on the button, values are moving as expected. But when I click on the submit button, the selected id's are not getting appended to database. I tried to do the same example and made some R&D also. But I didn't get expected results. I don't know what's wrong. Any logic/advice greatly appreciated.
Angularjs:
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
$scope.moveUp = function () {
for(var i = 0; i < $scope.vehicle.length; i++) {
var idx = $scope.peoples.indexOf($scope.vehicle[i])
console.log(idx);
if (idx > 0) {
var itemToMove = $scope.cars.splice(idx, 1)
console.log(itemToMove[0])
$scope.cars.splice(idx-1, 0, itemToMove[0]);
}
}
};
$scope.moveDown = function () {
var revVeh = $scope.vehicle.concat();
revVeh.reverse();
for(var i = 0; i < revVeh.length; i++) {
var idx = $scope.cars.indexOf(revVeh[i])
console.log(idx);
if (idx < $scope.cars.length) {
var itemToMove = $scope.cars.splice(idx, 1)
console.log(itemToMove[0])
$scope.cars.splice(idx+1, 0, itemToMove[0]);
}
}
};
});
This is my plnkr example(https://plnkr.co/edit/uyg99UO2Hm31AlLSBRAg)
I have created this plunker for your question answer
https://plnkr.co/edit/g49UoXTyAohVveNcw5eS?p=preview
Or CODE
HTML CODE :
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="main">
<options-up-down-directive option-to-process-up-down-of-keys="optionData"
option-to-select="dataToSelect1" class="col-5">
</options-up-down-directive>
</body>
</html>
JAVASCRIPT CODE :
var app = angular.module('app', []);
app.controller('main', function($scope){
$scope.optionData = ['abc', 'xyz', 'TDS'];
$scope.dataToSelect1 = {};
});
app.directive('optionsUpDownDirective',optionsUpDownDirective);
function optionsUpDownDirective() {
var directiveController = function($scope) {
var selfController = this;
var optionToProcessUpDownOfKeys = [];
var itemToMove = null;
$scope.optionToSelect.selectedData = null;
$scope.keyToMoveUpAndDown = $scope.optionToProcessUpDownOfKeys[0];
selfController.moveKeyUpAndDown = function(mode) {
optionToProcessUpDownOfKeys = $scope.optionToProcessUpDownOfKeys;
for(var i = 0, keysLength = $scope.optionToProcessUpDownOfKeys.length; i < keysLength; i++) {
if(optionToProcessUpDownOfKeys[i] == $scope.keyToMoveUpAndDown) {
var index = i;
console.log($scope.optionToSelect);
if ( index > 0 && mode === 'up') {
$scope.optionToSelect.selectedData = optionToProcessUpDownOfKeys.splice(index, 1);
$scope.optionToProcessUpDownOfKeys.splice(index-1, 0, $scope.optionToSelect.selectedData[0]);
} else if(mode === 'down'){
$scope.optionToSelect.selectedData = optionToProcessUpDownOfKeys.splice(index, 1);
$scope.optionToProcessUpDownOfKeys.splice(index+1, 0, $scope.optionToSelect.selectedData[0]);
}
break;
}
}
};
};
return {
restrict : 'E',
scope : {
optionToProcessUpDownOfKeys : "=?optionToProcessUpDownOfKeys",
optionToSelect: "=?optionToSelect"
},
template :`<select id="select" size="7" ng-model="keyToMoveUpAndDown" ng-options="key for key in optionToProcessUpDownOfKeys" ng-click="keyToChangeCtrl.enableUpOrDownButton(keyToMoveUpAndDown)">
</select>
<button ng-click="keyToChangeCtrl.moveKeyUpAndDown('up')" class="local-action-button" id="moveUp">
<i class="glyphicon glyphicon-arrow-up button-glyphicon-label-dis"></i>UP</button>
<button ng-click="keyToChangeCtrl.moveKeyUpAndDown('down')" class="local-action-button" id="moveDown">
<i class="glyphicon glyphicon-arrow-down button-glyphicon-label-dis"></i>DOWN</button>
</div>`,
controller : ['$scope', directiveController],
controllerAs : "keyToChangeCtrl"
};
}
I'm using ng-route to show a page called "london.htm" (in the same directory of my principal page) into this principal page, such this example:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<body ng-app="myApp">
<p>Main</p>
City 1
City 2
<p>Click on the links to read about London and Paris.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/london", {
templateUrl : "london.htm"
})
.when("/paris", {
templateUrl : "paris.htm"
});
});
</script>
</body>
</html>
This is my principal page, when I call <div ng-view></div> to show "london.htm" page:
<!DOCTYPE html>
<!-- saved from url=(0069)https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="images/puzzle.png" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="styles/angular-bootstrap-datepicker.css" />
<link rel="stylesheet" href="styles/mainBoot.css">
<link rel="stylesheet" href="styles/scrollbar.css">
<link rel="stylesheet" href="styles/noscroll_numberfield.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.js"></script> -->
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<script src="scripts/deployeePanel.js"></script>
<script src="scripts/rest-services.js"></script>
<script src="scripts/jquery.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<!-- <script src="scripts/emailchecker.js"></script> -->
<script src="scripts/angular-bootstrap-datepicker.js" charset="utf-8"></script>
<!-- <script src="scripts/number-directive.js"></script> -->
<script type="application/javascript"></script>
<title>Pannello dipendenti</title>
<!-- Bootstrap core CSS -->
<link href="./styles/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="./styles/dashboard.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style id="holderjs-style" type="text/css"></style></head>
<body ng-app="StaffManagement" ng-controller="StaffController" background="images/sfondoblu3.png">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand">FDDispenser</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>Pannello Dipendenti</li>
<li>Settings</li>
<li>Profile</li>
<li>Help</li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
</form>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="active">Aggiungi/Modifica Dipendente</li>
<li>Reports</li>
<li>Analytics</li>
<li>Export</li>
</ul>
<ul class="nav nav-sidebar">
<li>Nav item</li>
<li>Nav item again</li>
<li>One more nav</li>
<li>Another nav item</li>
<li>More navigation</li>
</ul>
<ul class="nav nav-sidebar">
<li>Nav item again</li>
<li>One more nav</li>
<li>Another nav item</li>
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div ng-view></div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<!-- <script src="./Dashboard Template for Bootstrap_files/jquery.min.js.download"></script> -->
<script src="./scripts/bootstrap.min.js.download"></script>
<script src="./scripts/docs.min.js.download"></script>
</body></html>
This is my js page when I make call ng-route:
var app = angular.module("StaffManagement", ['ng-bootstrap-datepicker','ngRoute']);
//Controller Part
app.controller("StaffController", function($scope, $filter, $http, restService) {
$scope.staffs = [];
$scope.staffLast = [];
$scope.staffForm = {
idstaff : -1,
staffType: {
idstaffType: 2,
type: "Dipendente"
},
name: "",
surname: "",
birthDate: "",
phone: "",
gender: true,
working: true,
staffLogin: {
idstaffLogin: -1,
email: "",
// pass: "",
}
};
$scope.staffLoginForm = {
idstaffLogin: -1,
email: "",
// pass: ""
};
$scope.selectg = [
{name:'uomo', type: true},
{name:'donna', type: false}
];
$scope.dateold = {
getdateold: ""
};
$scope.datepickerOptions = {
format: 'yyyy/mm/dd',
language: 'it',
startDate: "01/01/1900",
endDate: new Date(),
autoclose: true,
weekStart: 1
};
/*
$scope.emailcheck = function () {
$scope.answer = EmailChecker.emailc($scope.staffForm.staffLogin.email);
}
*/
//////////////////per il number controller
$scope.wks = {number: 1, name: 'testing'};
/////////////////////////////////////////
console.log($scope.staffForm.gender);
//Now load the data from server
_refreshStaffData();
//HTTP POST/PUT methods for add/edit country
// with the help of id, we are going to find out whether it is put or post operation
$scope.submitStaff = function() {
console.log($scope.staffForm);
if($scope.staffForm.name == "" || $scope.staffForm.surname == "" || $scope.staffForm.staffLogin.email == "" || $scope.staffForm.birthDate == "" || $scope.staffForm.phone == "" || $scope.staffForm.gender == null || $scope.staffForm.idstaff == null)
_showSBNoField();
else if(!_emailCheck($scope.staffForm.staffLogin.email))
_showSBInvalid();
/* else if(!angular._isDate($scope.staffForm.birthDate))
console.log("no date"); */
else{
if ($scope.staffForm.idstaff == -1) {
console.log("StaffLogin");
console.log($scope.staffForm.staffLogin);
console.log($scope.staffForm);
//Id is absent in form data, it is create new country operation
$scope.staffForm.birthDate = $filter('date')(new Date($scope.staffForm.birthDate), "yyyy-MM-dd");
console.log( $scope.staffForm.birthDate);
restService.insertstaff($scope.staffForm, _giveLast, _error);
/* $http({
method : 'POST',
url : 'http://localhost:8080/FoodDrinkDispener/rest/staff',
data : angular.toJson($scope.staffForm),
headers : {
'Content-Type' : 'application/json'
}
}).then( _giveLast, _error ); */
// console.log("StaffLogin");
} else {
//Id is present in form data, it is edit country operation
//var dateformat = new String($scope.staffForm.birthDate);
// $scope.getdateold.getdateold = $scope.staffForm.birthDate;
$scope.staffForm.birthDate = $filter('date')(new Date($scope.staffForm.birthDate), "yyyy-MM-dd");
console.log( $scope.staffForm.birthDate);
// $scope.staffForm.phone = $scope.staffForm.phone.toString();
// console.log( $scope.staffForm.phone);
// console.log( new Date($scope.staffForm.birthDate));
restService.updatestaff($scope.staffForm, _putStaffLogin, _error);
/* $http({
method : 'PUT',
url : 'http://localhost:8080/FoodDrinkDispener/rest/staff',
data : angular.toJson($scope.staffForm),
headers : {
'Content-Type' : 'application/json'
}
}).then( _putStaffLogin, _error ); */
}
console.log("HTTP: ");
console.log($http);
console.log($scope.staffForm.gender);
console.log($scope.staffForm.idstaff);
}
};
//HTTP DELETE- delete country by Id
/* $scope.deleteStaff = function(staff) {
$http({
method : 'DELETE',
url : 'http://localhost:8080/FoodDrinkDispener/rest/staff/' + staff.idstaff
}).then(_success, _error);
}; */
$scope.deleteStaff = function(staff) {
$scope.staffForm.name = staff.name;
$scope.staffForm.idstaff = staff.idstaff;
$scope.staffForm.surname = staff.surname;
$scope.staffForm.birthDate = staff.birthDate;
$scope.staffForm.phone = staff.phone;
// $scope.staffForm.gender = staff.gender;
$scope.selectg.type = staff.gender;
//$scope.staffForm.staffLogin.idstaffLogin = staff.staffLogin.idstaff;
$scope.staffForm.staffLogin.email = staff.staffLogin.email;
$scope.staffForm.staffLogin.staff = "";
$scope.staffForm.working = false;
// $scope.staffForm.pass = "prova";
console.log(staff.staffLogin.email);
restService.deletestaff($scope.staffForm, _success, _error);
}
// In case of edit, populate form fields and assign form.id with country id
$scope.editStaff = function(staff) {
console.log(staff.phone);
$scope.staffForm.name = staff.name;
$scope.staffForm.idstaff = staff.idstaff;
$scope.staffForm.surname = staff.surname;
// String a = staff.birthDate;
console.log(staff.birthDate);
// $scope.staffForm.birthDate = $filter('date')(staff.birthDate, "mm/dd/yyyy");
$scope.staffForm.birthDate = staff.birthDate;
console.log($scope.staffForm.birthDate);
$scope.staffForm.phone = parseInt(staff.phone, 10); // parseInt with radix;
$scope.staffForm.gender = staff.gender;
$scope.selectg.type = staff.gender;
//$scope.staffForm.staffLogin.idstaffLogin = staff.staffLogin.idstaff;
$scope.staffForm.staffLogin.email = staff.staffLogin.email;
$scope.staffForm.staffLogin.staff = "";
// $scope.staffForm.pass = "prova";
console.log(staff.staffLogin.email);
};
function _refreshStaffData() {
restService.allstaffworking(_getstaff, _timeout, _error);
}
function _getstaff(response){
if (response.data == ""){
console.log("Accesso non autorizzato")
}
$scope.staffs = response.data;
}
function _success(response) {
// console.log(staff.name);
console.log("successo");
_refreshStaffData();
_clearFormData();
_showSB();
console.log("cleared");
}
function _timeout() {
// console.log(staff.name);
console.log("timeout token");
_showSBtimeout();
}
function _error(response) {
console.log("qualcosa è andata male");
console.log(response.statusText);
}
//Clear the form
function _clearFormData() {
$scope.staffForm.idstaff = -1;
$scope.staffForm.name = "";
$scope.staffForm.surname = "";
$scope.staffForm.birthDate = "";
$scope.staffForm.phone = "";
$scope.staffForm.gender = true;
$scope.staffForm.staffLogin.idstaffLogin = -1;
$scope.staffForm.staffLogin.email = "";
// $scope.staffForm.staffLogin.pass = "";
$scope.staffForm.staffType.idstaffType=2;
$scope.staffForm.working= true;
};
function _giveLast(){
console.log("yes");
console.log($scope.staffForm);
// $scope.staffLast = restService.laststaff;
restService.laststaff(_postStaffLogin);
// _postStaffLogin();
}
function _postStaffLogin(response){
$scope.staffLast = response.data;
console.log($scope.staffForm.staffLogin.email);
console.log($scope.staffLast.idstaff);
//console.log($scope.staffForm.staffLogin.idstafflogin);
//$scope.staffForm.staffLogin.staff = $scope.staffLast;
//$scope.staffLoginForm.staff = $scope.staffLast;
$scope.staffForm.staffLogin.email;
// $scope.staffLoginForm.pass = $scope.staffForm.staffLogin.pass;
console.log($scope.staffLoginForm.idstaffLogin);
console.log($scope.staffLoginForm.email);
// console.log($scope.staffLoginForm.pass);
restService.insertstafflogin($scope.staffLoginForm, _success, _error);
}
function _putStaffLogin(){
console.log("CIAOOOO");
$scope.staffLoginForm.idstaffLogin = $scope.staffForm.idstaff;
$scope.staffLoginForm.email = $scope.staffForm.staffLogin.email;
// $scope.staffLoginForm.pass = "ab";
console.log($scope.staffLoginForm.idstaffLogin);
console.log($scope.staffLoginForm.email);
// console.log($scope.staffLoginForm.pass);
restService.updatestafflogin($scope.staffLoginForm, _success, _error);
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
function _showSBNoField() {
// Get the snackbar DIV
var x = document.getElementById("snackbar_nofield")
// Add the "show" class to DIV
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
function _showSBInvalid() {
// Get the snackbar DIV
var x = document.getElementById("snackbar_invalid")
// Add the "show" class to DIV
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
function _showSBtimeout() {
// Get the snackbar DIV
var x = document.getElementById("snackbar_timeout")
// Add the "show" class to DIV
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
function _isDate(value) {
return toString.call(value) === '[object Date]';
}
function _emailCheck(emailStr) {
var emailPat = /^(.+)#(.+)$/;
var specialChars = "\\(\\)<>#,;:\\\\\\\"\\.\\[\\]";
var validChars = "[^\\s" + specialChars + "]";
var quotedUser = "(\"[^\"]*\")";
var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom = validChars + "+";
var word = "(" + atom + "|" + quotedUser + ")";
var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
var matchArray = emailStr.match(emailPat);
if (matchArray == null) {
alert("L'email sembra essere sbagliata: (controlla # e .)");
return false;
}
var user = matchArray[1];
var domain = matchArray[2];
if (user.match(userPat) == null) {
alert("La parte dell'email prima di '#' non sembra essere valida!");
return false;
}
var IPArray = domain.match(ipDomainPat);
if (IPArray != null) {
for (var i = 1; i <= 4; i++) {
if (IPArray[i] > 255) {
alert("L'IP di destinazione non è valido!");
return false;
}
}
return true;
}
var domainArray = domain.match(domainPat);
if (domainArray == null) {
alert("La parte dell'email dopo '#' non sembra essere valida!");
return false;
}
var atomPat = new RegExp(atom, "g");
var domArr = domain.match(atomPat);
var len = domArr.length;
if (domArr[domArr.length - 1].length < 2 ||
domArr[domArr.length - 1].length > 6) {
alert("Il dominio di primo livello (es: .com e .it) non sembra essere valido!");
return false;
}
if (len < 2) {
var errStr = "L'indirizzo manca del dominio!";
alert(errStr);
return false;
}
return true;
}
});
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/editEmployee', {
templateUrl: 'london.htm',
});
}]);
Where I have added appconfig for ng-route:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/editEmployee', {
templateUrl: 'london.htm',
});
}]);
And this is the page that I want to show when I called the url: file:///C:/Users/Giacomo%20B/Desktop/progetto%20mainetti/prove%20angular/fddWebapp/edit_employee.html#/editEmployee , called "london.htm", a simple page to try it:
<!-- saved from url=(0043)http://www.w3schools.com/angular/london.htm -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"></head><body><h1>London</h1>
<h3>London is the capital city of England.</h3>
<p>It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
<p>{{msg}}</p></body></html>
In this way, it should works..but It doesn't work!!!
There are these errors:
angular.js:10765 XMLHttpRequest cannot load file:///C:/Users/Giacomo%20B/Desktop/progetto%20mainetti/prove%20angular/fddWebapp/london.htm. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
angular.js:12520 Error: [$compile:tpload] Failed to load template: london.htm (HTTP status: -1 )
http://errors.angularjs.org/1.4.8/$compile/tpload?p0=london.htm&p1=-1&p2=
I am trying to create a Carousel which is supposed to slide automatically in a particular time interval. Below is my code. For reference: onehungrymind.
Index.html
<!DOCTYPE html>
<html ng-app="SampleApp">
<head>
<meta charset="utf-8">
<title>Carousel</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<custom-carousel></custom-carousel>
<script src="js/jquery.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/angular-animate.min.js"></script>
<script src="js/angular-touch.min.js"></script>
<script src="js/TweenMax.min.js"></script>
<script src="carousel.js"></script>
</body>
</html>
carouselView.html
<div class="container slider">
<img ng-repeat="slide in slides" class="slide slide-animation nonDraggableImage"
ng-swipe-right="nextSlide()" ng-swipe-left="prevSlide()"
ng-hide="!isCurrentSlideIndex($index)" ng-src="{{slide.image}}"/>
<a class="arrow prev" href="#" ng-click="nextSlide()"></a>
<a class="arrow next" href="#" ng-click="prevSlide()"></a>
<nav class="nav">
<div class="wrapper">
<ul class="dots">
<li class="dot" ng-repeat="slide in slides">
<a href="#" ng-class="{'active':isCurrentSlideIndex($index)}"
ng-click="setCurrentSlideIndex($index);">{{slide.description}}</a></li>
</ul>
</div>
</nav>
</div>
carousel.js
var sampleApp = angular.module('SampleApp', ['ngAnimate', 'ngTouch']);
sampleApp.directive('customCarousel', function(){
var ctrl = function($scope){
$scope.slides = [
{image: 'images/img1.jpg', description: 'Image 00'},
{image: 'images/img2.jpg', description: 'Image 01'},
{image: 'images/img3.jpg', description: 'Image 02'},
{image: 'images/img4.jpg', description: 'Image 03'},
{image: 'images/img5.jpg', description: 'Image 04'}
];
$scope.direction = 'left';
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
$scope.prevSlide = function () {
$scope.direction = 'left';
$scope.currentIndex = ($scope.currentIndex < $scope.slides.length - 1) ? ++$scope.currentIndex : 0;
};
$scope.nextSlide = function () {
$scope.direction = 'right';
$scope.currentIndex = ($scope.currentIndex > 0) ? --$scope.currentIndex : $scope.slides.length - 1;
};
//$interval($scope.prevSlide(), 2000);
}
return {
restrict:'E',
controller:ctrl,
templateUrl:'carouselView.html'
};
}).animation('.slide-animation', function () {
return {
addClass: function (element, className, done) {
if (className == 'ng-hide') {
TweenMax.to(element, 0.5, {left: -element.parent().width(), onComplete: done });
}
else {
done();
}
},
removeClass: function (element, className, done) {
if (className == 'ng-hide') {
element.removeClass('ng-hide');
TweenMax.set(element, { left: element.parent().width() });
TweenMax.to(element, 0.5, {left: 0, onComplete: done });
}
else {
done();
}
}
};
});
Everything is working fine except auto slide. I did attempt to call prevSlide() and nextSlide() from a $interval service (commented line), But didn't work. Probably I am not injecting $interval service properly.
sampleApp.directive('customCarousel', ['$interval', function($interval){
//code
}]);
Output Screenshot
I'm having problem with javascript sort function. I have this function:
var compare = function(a, b) {
if(a.last_nom < b.last_nom) {
return -1;
}
if(a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
And the I call it with:
var sortedData = fullData.sort(compare);
But I don't know how to pass dates correctly.
You can find jsbin example here
Thank you in advance
As requested, to make sense of my code here is full code:
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.css" rel="stylesheet">
<link rel="icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mėmelio Žirafos - Facebook feeds page</title>
<style>
html {
overflow-y: scroll;
}
header {
margin-bottom: 50px;
}
.progress {
top: 50%;
width: 50%;
margin: 0 auto;
}
.event-only .not-event {
display: none;
}
.post-by {
display: block;
margin-bottom: 25px;
}
.post-date {
display: block;
}
.card .card-content .card-title {
line-height: 26px;
margin-bottom: 15px;
display: inline-block;
}
img.responsive-img {
width: 100%;
}
</style>
</head>
<body>
<div class="progress">
<div class="indeterminate"></div>
</div>
<div class="hide" id="content">
<!--header-->
<header>
<nav class="top-nav">
<div class="container">
<div class="nav-wrapper">
<p>Mėmelio Žirafos Facebook feeds page</p>
</div>
</div>
</nav>
</header>
<!--end header-->
<div class="container">
<div class="row">
<!--checkbox to show all posts or events only-->
<div class="col s6">
<p>
<input type="checkbox" id="events-only" />
<label for="events-only">Show events only</label>
</p>
</div>
<!--end checkbox-->
</div>
<div class="row">
<h3 class="center-align" id="posts-acc-title">Facebook posts</h3>
<!--posts wrapper-->
<div class="col s12" id="fb-posts-wrap"></div>
<!--end posts wrapper-->
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/1.4.1/sugar.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.js"></script>
<script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>
<script>
(function() {
/*
* Our Globals
*/
var html = '';
var finalData = [];
var token = 'CAAQYWWjo5zkBAGlqs2AxxsWKcgWEI0VM3UA7555dhCQEOCTu9VW91tpfaNvrt4tS0w8DkxPJHvRENRrMeDT9QC1aSvHdZA7nhw9ZBqZAyUhMM6PTQoJggn7pJRHEO8xQJp8lsGZAqixVU8SvrMlhUUhwmzB11h9ISqd3MvmoD4aVZBPPD1geO';
var baseURL =
'https://graph.facebook.com/v2.4/{slug}/feed?fields=picture,created_time,message,link,type,description,caption,full_picture,id,admin_creator,from&limit=50&access_token={token}';
var slugs = [{
slug: 'sisaidgallery',
complete: false
}, {
slug: 'duzenos',
complete: false
}, {
slug: 'bbcnews',
complete: false
}, {
slug: 'Klaipeda.renginiai',
complete: false
}, {
slug: 'PORTbyBarBara',
complete: false
}, {
slug: 'Kastonas',
complete: false
}, {
slug: 'klaipedosdramosteatras',
complete: false
}, {
slug: '238899589464193',
complete: false
}];
/*
* allComplete
*/
var allComplete = function() {
for (var i = 0; i < slugs.length; i++) {
if (slugs[i].complete === false) {
return false;
}
}
return true;
};
/*
* makeURL
*/
var makeURL = function(url, token, slug) {
return url.replace('{token}', token).replace('{slug}', slug);
};
/*
* Date formatter
*/
var dateFormatter = function(date) {
var dateFormat = '{HH}:{mm}, {Weekday}, {d} {Month}, {yyyy}';
return Date.create(date).format(dateFormat);
}
/*
* Mark slug as complete
*/
var completeSlug = function(mySlug) {
for (var i in slugs) {
if (slugs[i].slug === mySlug) {
slugs[i].complete = true;
}
}
};
var copyTextID = 100;
/*
* template
*/
var template = '' +
'<div class="card blue-grey darken-1 hoverable {isEvent}">' +
'<div class="card-content white-text">' +
'<span class="post-date">Posted on: {fb-post-date}</span>' +
'<span class="post-by">Post by: {fb-post-from}</span>' +
'<div class="row">' +
'<div class="col s2">' +
'<img class="responsive-img" src="{fb-image}" alt=""/>' +
'</div>' +
'<div class="col s10" id="post-target-{fb-post-id}">' +
'<span class="card-title">{fb-post-title}</span>' +
'<p>{fb-post-text}</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="card-action">' +
'<a target="_blank" href="{fb-post-link}">Open post</a>' +
'<a class="waves-effect waves-light btn white-text red darken-1 hoverable" data-clipboard-target="#post-target-{fb-post-id}"><i class="material-icons right">subject</i>Copy</a>' +
'</div>' +
'</div>';
/*
* checking title, text and images
*/
var replaceUndefined = function(str) {
return str === undefined ? '' : str;
};
var replaceImage = function(str) {
return str === undefined ? 'https://placehold.it/350x150' : str;
};
/*
* bindTemplate
*/
var bindTemplate = function(template, obj) {
return template
.replace('{isEvent}', obj.type === 'event' ? '' : 'not-event')
.replace('{fb-image}', replaceImage(obj.picture))
.replace('{fb-post-from}', obj.from.name)
.replace('{fb-post-title}', replaceUndefined(obj.description))
.replace('{fb-post-text}', replaceUndefined(obj.message))
.replace('{fb-post-link}', obj.link)
.replace('{fb-post-date}', dateFormatter(obj.created_time))
.replace(/{fb-post-id}/g, obj.id);
};
var makeAjax = function(fbUrl, next, slug) {
$.ajax({
url: fbUrl
}).done(function(data) {
next(data, slug);
});
};
/*
* renderTemplate
*/
var renderTemplate = function() {
$('#fb-posts-wrap').html(html);
};
/*
* makeAjaxCalls
*/
var makeAjaxCalls = function(slugs) {
slugs.forEach(function(slug) {
makeAjax(makeURL(baseURL, token, slug.slug), showAllPosts, slug.slug);
});
};
/*
* Flatten data
*/
var flattenData = function(data) {
var fullData = [];
var empty = [];
data.forEach(function(row) {
fullData.push(row.data);
});
return empty.concat.apply(empty, fullData);
};
var compare = function(a, b) {
if (a.last_nom < b.last_nom) {
return -1;
}
if (a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
var showAllPosts = function(data, slug) {
// Let's first mark this slug as complete
completeSlug(slug);
// And store our data
finalData.push(data);
if (allComplete()) {
// merge all data
var fullData = flattenData(finalData);
// sort all data and
var sortedData = fullData.sort(compare);
// build the html
sortedData.forEach(function(obj) {
html += bindTemplate(template, obj);
});
// call the renderTemplateFunction
renderTemplate();
// finally hide the progress bar
$('.progress').fadeOut();
$('#content').removeClass('hide');
}
};
/*
* Listen to the change in the checkbox
*/
$('#events-only').change(function() {
if ($(this).is(':checked')) {
// hide the non events with css
$('#fb-posts-wrap').addClass('event-only');
} else {
// show the non events with css
$('#fb-posts-wrap').removeClass('event-only');
}
});
/*
* Kick off
*/
makeAjaxCalls(slugs);
})();
</script>
</body>
</html>
What is last_nom? There is no such function in JS Date specification
Try this:
function compare(a, b) {
if (a.getTime() > b.getTime())
return 1;
if (a.getTime() < b.getTime())
return -1;
return 0
}
var sortedDatesArray = unsortedDatesArray.sort(compare);