I've a simple situation, where I've a bunch of data stored in an array.
I want to display the array in html view, one by one, when the next/prev buttons are clicked.
I followed this : How to show item from json Array one by one in Angular JS
However, My code doesn't seem to work.
Code :
/**
* Created by PBC on 5/21/2016.
*/
var solver = angular.module('solver', []);
solver.controller('data', data);
function data($scope, $http){
$scope.Type = "";
$scope.qlist = [];
$scope.alist = [];
$scope.idx = 0;
$scope.ans = "";
$scope.q = "";
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
var data = $.param({
_Down_Questions:localStorage.getItem('prb')
});
$http.post("../Php/download_questions.php", data, config).then
(
//Success Callback
function (res) {
$scope.Type = res.data.Type;
if ($scope.Type == 'Objective'){
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"]};
$scope.qlist[i] = data;
}
}
else{
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"], O:res.data.Data[i]["O"]};
$scope.qlist.push[i] = data;
}
}
},
//Error Callback
function () {
$scope.registrationResponse = "";
swal("Request couldn't be sent!", "", "error");
}
);
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
$scope.prev = function () {
if ($scope.idx > 0){
$scope.idx -= 1;
ans = $scope.alist[$scope.idx];
}
};
}
using this, in the html as :
<div data-ng-controller="data">
<div style="display: table;margin: 0 auto; width: 30%">
<div class="row container" style="margin-top: 50%">
<div class="col l12" data-ng-repeat="q in qlist track by $index" data-ng-show="$index == idx">
{{q[idx]["Q"]}}
</div>
<input placeholder="Answer" data-ng-model="ans" type="text" class="validate center">
<div class="row" style="display: table;margin: 0 auto; width: 100%">
<a class="waves-effect waves-light btn" data-ng-click="next()" style="display: table;margin: 0 auto; width: 50%">Next</a><br>
<a class="waves-effect waves-light btn" data-ng-click="prev()" style="display: table;margin: 0 auto; width: 50%">Previous</a>
</div>
</div>
</div>
</div>
What am I doing wrong ?
I've found the mistakes:
1)
{{q[idx]["Q"]}}
should be
{{q["Q"]}}
2)
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
Here, the condition was wrong :
it should be,
if ($scope.idx < $scope.qlist.length){
Related
I am building an eCommerce store website, and I am facing an issue. The function updateCartTotal doesn't work at all. The script is also added to the bottom of the HTML body.
Thanks in advance.
HTML:
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>
Javascript:
let cartIcon = document.getElementById("cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
var removeCartButtons = document.getElementsByClassName("material-symbols-outlined");
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem)
}
// Quantity Change //
var quantitInputs = document.getElementsByClassName("cart qty");
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
quantityChanged = (event) => {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
}
function updateCartTotal() {
var cartContainer = document.getElementsByClassName("cart-content")[0];
var cartBox = cartContainer.getElementsByClassName("cart-box");
var total = 0
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
var priceElement = cartBox.getElementsByClassName("cart-price")[0]
var quantityElement = cartBox.getElementsByClassName("cart-qty")[0]
price = parseFloat(priceElement.innerText.replace("£", ""))
quantity = quantityElement.value
total = total + (price * quantity)
}
document.getElementsByClassName("total-price")[0].innerText = total
}
i am expecting the total to update as the quantity changes, and the function to work
You have the following mistakes-
There is no element with the class name cart qty.
var quantitInputs = document.getElementsByClassName("cart qty");
quantityChanged function should have a function keyword.
You are using the same name variable cartBox in updateCartTotal function which is creating confusion-
var cartBox = cartContainer.getElementsByClassName("cart-box");
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
}
Now, after fixing these mistakes, your code will look like the below which is working.
Note- I moved all the declarations to the top and I replaced those two methods-
getElementsByClassName() = querySelectorAll()
getElementsByClassName()[0] = querySelector()
let cartIcon = document.querySelector("#cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
var quantitInputs = document.querySelectorAll(".cart-qty");
var removeCartButtons = document.querySelectorAll(".material-symbols-outlined");
var cartContainer = document.querySelector(".cart-content");
var cartBox = cartContainer.querySelectorAll(".cart-box");
var totalEl = document.querySelector(".total-price")
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem);
}
// Quantity Change //
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
function quantityChanged(event) {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
};
function updateCartTotal() {
var total = 0;
for (var i = 0; i < cartBox.length; i++) {
var cartBoxEl = cartBox[i];
var priceElement = cartBoxEl.querySelector(".cart-price");
var quantityElement = cartBoxEl.querySelector(".cart-qty");
price = parseFloat(priceElement.innerText.replace("£", ""));
quantity = quantityElement.value;
total = total + price * quantity;
}
if (totalEl) {
totalEl.innerText = total;
}
}
<div>
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>
I am trying to filter through two JSON array objects in order to display selected results from the arrays. I am using two For Loops and an If Statement to filter out what needs to be shown.
However my issue comes in that the If Statement does not seem to filter out the results of the For Loop. Every item in the JSON object is displayed. Please help.
angular/javascript
var url = generateQuery('GET', '/products', CONFIG, params);
$scope.result = "";
var i;
var j;
$scope.items = [];
$http.get(url)
.success(function(data, status, headers, config) {
$scope.result = data;
for (i = 0; i < $scope.result.products.length; i++) {
for (j = 0; j < $scope.result.products[i].categories.length; j++) {
$scope.category_limit = $scope.result.products[i].categories[j];
if ($scope.category_limit = 'Jewellery') {
$scope.items.push({
image: $scope.result.products[i].featured_src,
name: $scope.result.products[i].title,
price: '$' + $scope.result.products[i].price + ' (R' + ($scope.result.products[i].price * $scope.convert.results.rate.Rate).toFixed(2) + ')',
id: $scope.result.products[i].id,
cat: $scope.category_limit
});
$ionicLoading.hide();
} else {
$ionicLoading.hide();
}
}
}
})
html
<div class="category-col" ng-repeat="i in items" id="swap_row_col">
<a ng-href="#/app/products/{{i.id}}" href="#/app/products/{{i.id}}" class="no-underline">
<img src= {{i.image}} class="category-image-col">
<!--<img src='images/add_to_cart.png' style="height: 24px; width: 28px; z-index: 5; position: fixed; margin-left: 34%; margin-top: -13%;"> -->
<div class="category-name-col"> {{i.name}} </div>
<div class="category-price-col"> {{i.price}} </div>
<div class="category-price-col"> {{i.cat}} </div>
</a>
</div>
i think your missing the == sign
if ($scope.category_limit == 'Jewellery'){
.....
}
I have a problem.
.titel
{
display: inline-block;
padding:5px 0 ;
}
#sort div div
{
display: inline-block;
padding:5px 0 ;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div>
<div class="titel achternaam" >Achternaam</div>
<div class="titel voornaam" >Voornaam</div>
<div class="titel kantoor" >Kantoor</div>
</div>
<div class="spann">
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
</div>
<div id="sort">
<div class="someaspcode" onClick="someaspcodethatifyouclickitwilgotothepage">
<div class="achternaam">bill</div>
<div class="voornaam">gates</div>
<div class="kantoor">123</div>
</div>
<div class="someaspcode" onClick="someaspcodethatifyouclickitwilgotothepage">
<div class="achternaam">jhonny</div>
<div class="voornaam">depp</div>
<div class="kantoor">43321</div>
</div>
The data from div with id sort comes from a database (thats the reason ,that I show it like this)
What I whant to do is :
If I click on the first icon it shows the list sorted by voornaam(asc)
If I click on the second icon it shows the list sorted by voornaam(desc)
If I click on the third icon it shows the list sorted by achternaam (asc)
and so further
I have tried everything that I found on stackoverflow and google but none of it worked.
Can someone give me a good piece of advice.
what i whant is something like this
http://jsfiddle.net/7sgw21hn/1/
but it must read the content
things i tried
jQuery - Sorting div contents
https://www.sitepoint.com/community/t/sort-div-order-alphabetically-based-on-contents/39955/2
and many more (can't find it right now)
this is before i click
and this is after
can we do something about this
Here's the demo: http://output.jsbin.com/gojopuh
As mentioned, the first two buttons sort asc and desc on first name.
The second two buttons sort asc and desc on last name.
My code uses bubble sort and takes advantage of replaceChild for performance benefits.
Also with the code below, adding more controls for this data is now trivial.
Code below, any questions just ask.
var controls = document.querySelectorAll('.spann > span');
var dataContainer = document.querySelector('#sort');
var data = document.querySelectorAll('#sort > div');
// select controls
var ascAchternaam = controls[0];
var descAchternaam = controls[1];
var ascVoornaam = controls[2];
var descVoornaam = controls[3];
var ascKantoor = controls[4];
var descKantoor = controls[5];
var ascVerjaardag = controls[6];
var descVerjaardag = controls[7];
// define a user type
function User(achternaam, voornaam, kantoor, verjaardag, elem) {
this.achternaam = achternaam;
this.voornaam = voornaam;
this.kantoor = kantoor;
this.verjaardag = verjaardag;
this.elem = elem;
}
function bubbleSort(order, data, prop) {
// copy data array
var sortingArr = Array.prototype.slice.call(data);
for (var i = sortingArr.length - 1; i >= 0; i--) {
for (var j = 1; j <= i; j++) {
var birthdayA = sortingArr[j-1][prop].split('-');
var birthdayB = sortingArr[j][prop].split('-');
if (order == 'asc') {
if (birthdayA.length > 1) {
if (parseFloat(birthdayA[1], 10) > parseFloat(birthdayB[1], 10) || parseFloat(birthdayA[0], 10) > parseFloat(birthdayB[0], 10)) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
} else {
if (sortingArr[j-1][prop] > sortingArr[j][prop]) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
}
} else {
if (birthdayA.length > 1) {
if (parseFloat(birthdayA[1], 10) < parseFloat(birthdayB[1], 10) || parseFloat(birthdayA[0], 10) < parseFloat(birthdayB[0], 10)) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
} else {
if (sortingArr[j-1][prop] < sortingArr[j][prop]) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
}
}
}
}
return sortingArr;
}
// event action
function sortOnClick(order, data, prop) {
var sorted = bubbleSort(order, data, prop);
for (var i = 0; i < sorted.length; i++) {
var user = sorted[i];
var wrapper = user.elem.cloneNode(true);
dataContainer.replaceChild(wrapper, dataContainer.children[i]);
}
return sorted;
}
// used to make the data into a format we need
function formatUsers(data) {
var userData = [];
for (var i = 0; i < data.length; i++) {
var userElem = data[i];
var fname = userElem.querySelector('.achternaam').textContent;
var lname = userElem.querySelector('.voornaam').textContent;
var office = userElem.querySelector('.kantoor').textContent;
var birthday = userElem.querySelector('.verjaardag').textContent;
userData.push(new User(fname, lname, office, birthday, userElem));
}
return userData;
}
// sorter
function initSorter(data) {
// reshape our data
var userData = formatUsers(data);
// add event listeners to controls
ascAchternaam.addEventListener('click', function() {
sortOnClick('asc', userData, 'achternaam');
});
descAchternaam.addEventListener('click', function() {
sortOnClick('desc', userData, 'achternaam');
});
ascVoornaam.addEventListener('click', function() {
sortOnClick('asc', userData, 'voornaam');
});
descVoornaam.addEventListener('click', function() {
sortOnClick('desc', userData, 'voornaam');
});
ascKantoor.addEventListener('click', function() {
sortOnClick('asc', userData, 'kantoor');
});
descKantoor.addEventListener('click', function() {
sortOnClick('desc', userData, 'kantoor');
});
ascVerjaardag.addEventListener('click', function() {
sortOnClick('asc', userData, 'verjaardag');
});
descVerjaardag.addEventListener('click', function() {
sortOnClick('desc', userData, 'verjaardag');
});
}
// init our sorter
initSorter(data);
Let's give this a try then.
You do have to edit your HTML structure so that each 'record' of first name, last name and office has a seperate container. If you also have to go counting the amout of divs that make up one record, the code grows even larger.
I opted for a list as the wrappers, as it's more or less the standard way.
Also added a data-sort attribute to each of the icons so I don't have to go through the hassle of reading the sort type from the header.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.wrap-3, .wrap-6 {
border: 1px solid black;
width: 50%;
}
.wrap-3 > * {
display: inline-block;
width: 32%;
}
.wrap-6 > * {
display: inline-block;
width: 16%;
}
ul {
border: 1px solid black;
list-style: none;
width: 50%;
}
li {
display: block;
width: 100%;
}
li > * {
display: inline-block;
width: 32%;
}
</style>
</head>
<body>
<div class="wrap-3">
<span class="titel achternaam" >Achternaam</span>
<span class="titel voornaam" >Voornaam</span>
<span class="titel kantoor" >Kantoor</span>
</div>
<div id="icons-sort" class="wrap-6">
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="achternaam-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="achternaam-desc">down</span>
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="voornaam-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="voornaam-desc">down</span>
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="kantoor-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="kantoor-desc">down</span>
</div>
<ul>
<li>
<span class="achternaam">Gates</span>
<span class="voornaam">Bill</span>
<span class="kantoor">123</span>
</li>
<li>
<span class="achternaam">Zuckerberg</span>
<span class="voornaam">Mark</span>
<span class="kantoor">456</span>
</li>
<li>
<span class="achternaam">Resig</span>
<span class="voornaam">John</span>
<span class="kantoor">789</span>
</li>
</ul>
<script>
var clear = function clear( node ) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
return node;
};
document.querySelector('#icons-sort').addEventListener('click', function( event ) {
var list, records, fragment, sortType, field, order;
if (event.target && event.target.hasAttribute('data-sort')) {
list = document.querySelector('ul'),
records = Array.prototype.slice.call(list.querySelectorAll('li')),
fragment = document.createDocumentFragment(),
sortType = event.target.getAttribute('data-sort').split('-'),
field = '.' + sortType[0],
order = sortType[1];
records = records.sort(function( first, second ) {
var firstVal = first.querySelector(field).innerHTML,
secondVal = second.querySelector(field).innerHTML;
if (firstVal < secondVal) return -1;
else if (firstVal > secondVal) return 1;
});
if (order === 'desc') records.reverse();
records.forEach(function( listItem ) {
fragment.appendChild(listItem);
});
clear(list).appendChild(fragment);
}
});
</script>
</body>
</html>
I am building an app using google's QPX express and I created a service to call the QPX web service.
I noticed that when I inspect certain functions, I see that they are executing indefinitely. The functions are $scope.pageArray, $scope.humanizeTime.Can someone help me identify why this is the case.
I have an understanding of why this is happening, but am not able to identify the root cause. Somehow/Somewhere in the code I am suggesting to Angular that the model has changed and therefore Angular is running a $scope.$digest, but I cant seem to identify where.
var resultController =planeSearchControllers.controller('resultController',['$scope','$http','commonSharedService','flight', function($scope,$http,commonSharedService,flight){
var isDebugEnabled = true;
$scope.showResults = false;
$scope.showPlaneSearch = true;
$scope.showPlaneError = false;
$scope.planeView = false;
$scope.historyView = false;
$scope.$watch(function() {return commonSharedService.getMode();},function(newValue,oldValue){
console.log('New Mode is' + newValue);
if(newValue == 'plane'){
$scope.planeView = true;
$scope.historyView = false;
$scope.historyObj = [];
}else if(newValue == 'history'){
getHistory(commonSharedService.getUserName());
$scope.planeView = false;
$scope.historyView = true;
}
});
$scope.$watch(function (){return commonSharedService.getValidateInputs();},function (newValue,oldValue){
if(isDebugEnabled){
console.log('Value is changed for getValidateInputs ' + 'New Value is -->'+ newValue);
}
$scope.validateInputs = newValue;
if($scope.validateInputs == true) {
makePlaneCall();
$scope.showResults = true;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
if($scope.validateInputs == false) {
$scope.showResults = false;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
});
$scope.humanizeTime = function(time){
//var duration = new moment.duration(time, "minutes");
//var hours = duration.hours();
//var minutes = duration.minutes();
var hours = Math.floor(time/60);
var minutes = time - (60 * hours);
var str = hours == 0 ? '': hours + 'hours ' ;
str += minutes == 0 ? '': minutes + 'minutes';
return str;
};
//Page Filtering
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.numPages = function () {
if($scope.tripOption!=null )
return Math.ceil($scope.tripOption.length / $scope.numPerPage);
else
return 0;
};
$scope.pageArray = function () {
var input = [];
for(var i=0;i<$scope.numPages();i++){
input[i] = i+1;
}
return input;
};
var paging = function(arrayIn,pageNo,perPageNo){
var outArray = [];
if(arrayIn!=undefined){
var from = perPageNo * (pageNo-1);
var to = from + perPageNo;
if (to > arrayIn.length)
to= arrayIn.length;
//console.log(from);
//console.log(to);
//console.log(outArray);
for (var i =from; i<to ;i++)
outArray.push(arrayIn[i]);
}
return outArray;
};
$scope.paginationFilter = function (){
return paging($scope.tripOption,$scope.currentPage,$scope.numPerPage);
};
var makePlaneCall = function () {
$scope.appendObj = commonSharedService.getAppendObj();
$scope.jsonObj = commonSharedService.getJsonObj();
$scope.jsonObj['time'] = moment().format("ddd Do,YYYY HH:mm a");
var user = commonSharedService.getUserName();
if(user != undefined)
setHistory(user,$scope.jsonObj);
$scope.planeRequest = {};
$scope.requestObj = {};
var slice = [];
var slice1 ={};
var slice2 ={};
var slice3 ={};
{
slice1['origin'] = $scope.appendObj['departAirport'];
slice1['destination']= $scope.appendObj['multiCity'] ? $scope.appendObj['interimAirport'] :$scope.appendObj['arrivalAirport'];
slice1['date']= $scope.appendObj['departureDate'];
slice1['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['departureEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice1['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice1);
}
if($scope.appendObj['multiCity'] == true){
slice2['origin'] = $scope.appendObj['interimAirport'];
slice2['destination']= $scope.appendObj['arrivalAirport'];
slice2['date']= $scope.appendObj['interimDate'];
slice2['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['interimEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice2['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice2);
}
if($scope.appendObj['isReturnFlight'] == 'true'){
slice3['origin']=$scope.appendObj['arrivalAirport'];
slice3['destination'] = $scope.appendObj['departAirport'];
slice3['date']=$scope.appendObj['arrivalDate'];
slice3['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['arrivalEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice3['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice3);
}
for(var property in $scope.jsonObj){
if($scope.jsonObj.hasOwnProperty(property)){
$scope.requestObj[property] = $scope.jsonObj[property];
}
}
$scope.requestObj['slice'] = slice;
//$scope.requestObj['passengers'] = $scope.jsonObj['passengers'];
$scope.requestObj['solutions'] = 5;
$scope.requestObj['refundable'] = false;
$scope.planeRequest['request'] =$scope.requestObj;
flight.search($scope.planeRequest,function(response){
$scope.result= response;
$scope.info = $scope.result.trips.data;
$scope.tripOption = $scope.result.trips.tripOption;
//console.log($scope.tripOption);
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
}
}
else{
$scope.showPlaneError = true;
$scope.planeSearchErrorMsg = "No Solutions found. Please check your airport codes and set more liberal parameter for the search to see if something turns up.";
}
console.log(response);
},function(response){
console.log("error");
$scope.result= response;
console.log(response);
});
};
function setHistory(userName,historyObj){
var firstTime=true;
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var historyRef = ref.child(userName);
historyRef.on("value", function(historySnapshotObj) {
if(firstTime==true){
var historySnapshot = historySnapshotObj.val();
console.log(historySnapshot);
var count;
if(historySnapshot!=null)
count = historySnapshot['count'];
console.log(count);
var obj ={};
if(count == undefined) {
obj['count'] = 0;
obj[0]= historyObj;
}else if(count < 9){
obj['count'] = ++count;
obj[count]= historyObj;
}else if(count == 9){
console.log(3);
obj['count'] = count;
for(var i=0;i<9;i++)
obj[i+1] = historySnapshot[i];
obj[0] = historyObj;
}
firstTime = false;
historyRef.update(obj);
}
else {
console.log("Wrong Place");
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
function getHistory(userName){
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var usersRef = ref.child(userName);
usersRef.on("value", function(snapshot) {
for (var i=0;i<10;i++){}
var userHistory = snapshot.val();
var count;
var array=[];
if(userHistory!=null)
count = userHistory['count'];
if (count!=undefined) {
for (var i=0;i <count ; i++)
array.push(userHistory[i]);
}
$scope.historyObj = array;
$scope.$digest();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
}]);
I tested all functions and all of them seem to be working , except that when I added the pagination I dont see any result.
P.S : I was using a filter before , but for the sake of debug , I moved the pagination logic into the controller. I also understand that I could have used a directive.(since I am displaying the result at only place, I decided to skip it.)
I am also adding the view below , in which I am using the controller.
<!-- Result Body-->
<div class="col-sm-6 col-md-6 col-lg-7" data-ng-controller="resultController">
<div class="container-fluid">
<div data-ng-show="planeView">
<div data-ng-hide="showResults">
<div><span></span><span>{{errorMsg}}</span></div>
</div>
<div data-ng-show="showResults">
<div class="showPlaneSearch" data-ng-show="showPlaneSearch">
<div class="query thumbnail">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<span >Page</span>
<select data-ng-model="currentPage" id="selectPage" class="form-control col-xs-5 col-sm-5 col-md-5 col-lg-5"
data-ng-options="value for value in pageArray()" data-toggle="popover" data-trigger="hover" data-placement="right"
data-content="Select Page Number">
</select>
</div>
</div>
</div>
<ul class="planesResult">
{{currentPage}}
{{numPerPage}}
<li ng-repeat="trip in paginationFilter" class="thumbnail">
<div class="row phoneContents">
<!-- Image -->
<div class="hidden-xs hidden-sm hidden-md col-lg-2">
<img src="images/Airplane-Icon.png" />
</div>
<!-- Trip Total $$$ -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10" >
<span class="price">{{trip.saleTotal}}</span>
</div>
<!-- Everything except Image -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<!--Each Slice -->
<div ng-repeat="slice in trip.slice" class="slice row">
<!-- Each Segment Origin-->
<span class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-repeat="segment in slice.segment">
<span > {{segment.leg[0].origin}}--></span>
<span ng-show="$last"> {{segment.leg[0].destination}} </span>
</span>
</span>
<!-- Each Segment Origin-->
<span class="col-xs-12 col-sm-3 col-md-3 col-lg-3">{{humanizeTime(slice.duration)}}</span>
<span ng-repeat="segment in slice.segment" class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-show="$first"> Depart at {{}} </span>
</span>
<br>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="showPlaneError" data-ng-show="showPlaneError">
<span class="thumbnail">{{planeSearchErrorMsg}}</span>
</div>
</div>
</div>
<div data-ng-show="historyView">
<pre>{{historyObj | json}}</pre>
</div>
</div>
</div>
I can't run code, but i see something suspicious, worth changing:
two places:
$scope.paginationFilter = function (){
return paging($scope.tripOption,
and
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
I see that when tripOption!= null you call paginationFilter function, which uses tripOption.
Hi I am new to Angularjs. I am changing the $scope variable on dropdown list selection. that scope variable is used for ng-repeat on div.
html code:
<div class="col-md-6" ng-repeat="model in FilteredModels | filter:{ModelText : '!All models'}:true">
<div class="well">
<div class="media">
<div class="media-object small"><i class="pp-car"></i></div>
<div class="media-body">
<div class="text-box">
<h3>{{model.ModelText}}</h3><span class="hr-small"></span>
</div>
<div class="dashboard-control clearfix">
<div class="simple-metric text-left sub-metric">
<div class="metric-title">Satisfaction score</div>
<div class="metric-number text-red">{{model.SatisfactionAvg | number:2}}</div>
</div>
<div class="simple-metric text-left sub-metric">
<div class="metric-title">Total interviews</div>
<div class="metric-number">{{model.TotalInterviews}}</div>
</div>
</div>
<ul class="list-standard">
<li> View interviews</li>
</ul>
</div>
</div>
</div>
</div>
angularjs code :
function filtermodelbyId() {
$scope.FilteredModels = [];
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
});
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
}
On change of dropdown list this filtermodelbyId() function gets call and i am pushing new values but this gets reflected after the second change on dropdown list.
is there any better way to represent this.
Thanks.
Seems like you are not using $http in dataFactory.getModelIdByFilter .
try using
$scope.$apply(function(){
$scope.FilteredModelIds = result.data;
});
Or else you can use angular services to load data (Assuming that you are using jquery ajax.)
You need to write if after $scope.FilteredModelIds is set
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
});
Just of quick wild guess:
function filtermodelbyId() {
$scope.FilteredModels = [];
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
});
}
Change the model array in the callback.