Angular 1 Error: [ng:areq] - Controller inside Controller - javascript

I'm trying to use angular rating from this http://plnkr.co/edit/kFKejRU0G2wmkD7GlNdH?p=preview
Here is my Angular code:
var ProfileApp = angular.module('ProfileApp', ['ui.bootstrap']);
ProfileApp.controller('getprofile', function($scope, $http) {
//Some codes are here
})
var RatingDemoCtrl = function ($scope) {
$scope.myRate = 0;
$scope.submit = function() {
console.log($scope.percent) ; //null
}
$scope.rate = 1;
$scope.max = 5;
$scope.isReadonly = false;
$scope.percent = 20;
$scope.hoveringOver = function(value,object) {
console.log('hoveringOver', value);
$scope.overStar = value;
$scope.percent = (100 * $scope.overStar) / $scope.max;
};
$scope.hoveringLeave = function(rate) {
console.log('hoveringLeave', $scope.rate);
$scope.percent = (100 * $scope.rate) / $scope.max;
};
};
Above code is used for Rating.
Here is the html code.
<body id="home" ng-app="ProfileApp">
<div ng-controller="getprofile">
//Some html codes
<div ng-controller="RatingDemoCtrl" class="well well-small">
<form class="Scroller-Container" ng-submit="submit()" ></form>
<rating value="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="hoveringLeave(rate)" ></rating>
<span class="badge" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">{{percent}}%</span>
<input type="submit" id="submit" value="Submit" />
</form>
<pre>{{percent}}</pre>
</div>
As you can see I have nested controller and this is giving me error Error: [ng:areq].
What can be done now? Is there any way I can fix it?
Update
After using the code of saj now I am getting error.
angular.min.js:101 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.2/ngRepeat/dupes?p0=r%20in%20range&p1=object%3A10&p2=%7B%22stateOn%22%3Anull%2C%22stateOff%22%3Anull%7D
No star is vising. I inspect the code and codes are below.
<div ng-controller="RatingDemoCtrl" class="well well-small ng-scope">
<form class="Scroller-Container ng-pristine ng-valid" ng-submit="submits()"></form>
<span ng-mouseleave="reset()" value="rate" max="max" readonly="readonly" on-hover="hoveringOver(value)" on-leave="hoveringLeave(rate)" class="ng-isolate-scope">
<!-- ngRepeat: r in range -->
</span>
<span class="badge ng-binding badge-warning ng-hide" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">20%</span>
<input type="submit" id="submit" value="Submit">
<pre class="ng-binding">20</pre>
</div>

You just need to separate out 'RatingDemoCtrl' controller
app.controller('RatingDemoCtrl', function($scope) {
$scope.myRate = 0;
$scope.submit = function() {
console.log($scope.percent); //null
}
$scope.rate = 1;
$scope.max = 5;
$scope.isReadonly = false;
$scope.percent = 20;
$scope.hoveringOver = function(value, object) {
console.log('hoveringOver', value);
$scope.overStar = value;
$scope.percent = (100 * $scope.overStar) / $scope.max;
};
$scope.hoveringLeave = function(rate) {
console.log('hoveringLeave', $scope.rate);
$scope.percent = (100 * $scope.rate) / $scope.max;
};
});
WORKING DEMO

Related

How To Implement Server Side Filtering And Pagination In AngularJS

I am using AngularJS to show data from database, i have implement a Client Side Pagination and Filtering on it but when it load huge data my App becomng crash.
so, i wonder to change it to server side pagination by limit the data until 10 item / page, it's done but when i'm do filtering data, it's only search to displayed item on page. This is my code so far
var app = angular.module('peradmin', ['ngRoute', 'ngAnimate']);
var baseUrl = 'http://localhost/peradmin/';
var currentUrl = window.location.pathname.split('/');
app.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start;
return input.slice(start);
}
return [];
}
});
app.controller('CustomerController', function($scope, $http, filterFilter) {
$scope.customer = [];
$scope.filtered = [];
$scope.pageSize = 10;
$scope.currentPage = 0;
$scope.getCustomerData = function(currentPage) {
$http({
method: 'POST',
url: baseUrl + 'customer/getcustomer',
data: { limit: $scope.pageSize, offset: currentPage },
headers: { 'Content-Type': 'application/json' }
}).then(function(response) {
$scope.customer = response.data.customer;
$scope.totalData = response.data.total;
$scope.pageNumber = Math.ceil($scope.totalData / $scope.pageSize);
})
}
$scope.filterData = function() {
$scope.currentPage = 0;
$scope.pageNumber = Math.ceil($scope.filtered.length / $scope.pageSize);
};
$scope.$watchCollection('customer', function() {
if ($scope.results == undefined) return;
$scope.currentPage = 0;
$scope.pageNumber = Math.ceil($scope.totalData / $scope.pageSize);
})
// Next & Previous Button
$scope.paging = function(type) {
if (type == 0 && $scope.currentPage > 0) {
--$scope.currentPage;
} else if (type == 1 && $scope.currentPage < $scope.pageNumber - 1) {
++$scope.currentPage;
}
$scope.getCustomerData($scope.pageSize * $scope.currentPage);
}
// Back to First Page
$scope.firstPage = function() {
$scope.currentPage = 0;
$scope.getCustomerData($scope.pageSize * $scope.currentPage);
}
// Go to Last Page
$scope.lastPage = function() {
$scope.currentPage = $scope.pageNumber - 1;
$scope.getCustomerData($scope.pageSize * $scope.currentPage + 1);
}
// call data when page is loaded
$scope.getCustomerData($scope.currentPage);
});
And this is my view :
<div class="well" id="formsearch">
<form id="search-form" class="form-inline float-lg-right" action="" method="POST">
<input type="text" class="form-control" placeholder="Name" name="name" id="name" ng-model="filter.NAME" ng-change="filterData()">
<input type="text" class="form-control" placeholder="Email" name="email" id="email" ng-model="filter.EMAIL" ng-change="filterData()">
</form>
</div>
<div class="box">
<div class="box-body table-responsive" ng-controller="CustomerController">
<label>Page {{ currentPage + 1 }} from {{ pageNumber }} | Total: {{ totalData }} Data</label>
<br><br>
<table class="table table-hover table-bordered table-striped" width="100%">
<thead>
<tr>
<th style="text-align:center;width:20%;">Email</th>
<th style="text-align:center;width:25%;">Name</th>
<th style="text-align:center;width:10%;">Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="val in $parent.filtered = (customer | filter:{NAMA:filter.NAME,EMAIL:filter.EMAIL})">
<td>{{ val.EMAIL }}</td>
<td>{{ val.NAME }}</td>
<td style="text-align:center;">{{ val.CUST_TYPE == "B" ? "Business": "Personal"}}</td>
</tr>
</tbody>
</table>
<ul class="pagination" ng-if="totalData > 0">
<li>First Page</li>
<li>Previous</li>
<li>Next</li>
<li>Last Pager</li>
</ul>
<div class="alert alert-danger" ng-if="totalData == 0"><center>Data Is Not Found</center></div>
</div>
</div>
how to make it filter to whole data on database?
Thanks
I think it should be:
$http({
method: 'POST',
url: baseUrl + 'customer/getcustomer',
data: {
limit: $scope.pageSize,
offset: currentPage,
filter: {
name: $scope.filter.NAME,
email: $scope.filter.EMAIL
}
},
headers: { 'Content-Type': 'application/json' }
})
Then on server side, wtih these 2 filter properties, you can perform database side filtration
Also, you need button to apply filters or throttle on your change handler:
$scope.filterData = function() {
$scope.currentPage = 0;
$scope.pageNumber = Math.ceil($scope.filtered.length / $scope.pageSize);
$scope.getCustomerData($scope.currentPage);
};
To perform throttle you can try ng-model-options='{ debounce: 1000 }':
<input type="text" ng-model-options='{ debounce: 1000 }' class="form-control" placeholder="Name" name="name" id="name" ng-model="filter.NAME" ng-change="filterData()">
<input type="text" ng-model-options='{ debounce: 1000 }' class="form-control" placeholder="Email" name="email" id="email" ng-model="filter.EMAIL" ng-change="filterData()">

Getting Uncaught Error: [$injector:modulerr]

I'm new to angular, and in the middle of refactoring my app to match John Papa's style of angular 1. However, this seem to break my views. I get Uncaught Error: [$injector:modulerr]. I'm referencing his style guide to look around but I find nothing out of place... but I want to say there's something wrong with how I'm injecting $http
app-controller.js:
(function() {
'use strict';
angular
.module('App.app-controller')
.controller('ChocoListCtrl', ChocoListCtrl);
ChocoListCtrl.$inject = ['$http'];
function ChocoListCtrl($http) {
var vm = this;
vm.getItemData;
vm.addItemToCart;
vm.cartTotal;
vm.addItemToCart;
vm.removeItem;
vm.getTotalQuantity;
vm.clearCart;
vm.cart = [];
function getItemData(){
return $http.get('../data/inventory.json').then(function(data){
vm.products = data.data;
})
}
function addItemToCart(choc) {
var cartItem = readCartItem(choc.id);
if(cartItem == null) {
//if item doesn't exist, add to cart array
vm.cart.push({type: choc.type, id: choc.id, price: choc.price, quantity: 1})
} else {
//increase quantity
cartItem.quantity++;
}
}
function cartTotal() {
var sum = 0;
vm.cart.forEach(function(item) {
sum += item.price * item.quantity;
});
return sum;
}
function getTotalQuantity() {
var totalItems = 0;
vm.cart.forEach(function(item) {
totalItems += item.quantity;
});
return totalItems;
}
function clearCart() {
vm.cart.length = 0;
}
function removeItem(choc) {
vm.cart.splice(choc, 1)
}
function readCartItem(id) {
//iterate thru cart and read ID
for(var i=0; i<vm.cart.length; i++) {
if(vm.cart[i].id === id) {
return vm.cart[i]
}
}
return null;
}
}
})();
app-module.js:
(function(){
'use strict';
angular.module('App.app-controller', []);
})();
app-directive.js:
(function(){
'use strict';
angular
.module('App.app-controller')
.directive('modalDialog', [function() {
return {
scope: {
cart: '=',
show: '=',
close:'&'
},
link: function(scope) {
scope.clearCart = function(){
scope.cart.length = 0;
scope.close();
}
scope.removeItem = function(choc){
scope.cart.splice(choc,1);
}
scope.cartTotal = function(){
var sum = 0;
scope.cart.forEach(function(item){
sum += item.price * item.quantity;
});
return sum;
}
},
templateUrl: '../modal.html'
}
}])
})();
and my view
<body ng-app="App">
<header class="header">
<div class="header-title">
<h1 class="text-center">SUPER SWEET CHOCOLATE SWEETS</h1>
</div>
</header>
<div ng-controller="ChocoListCtrl">
<section class="container">
<div ng-repeat="(title, chocolates) in products">
<div class="col-md-10">
<h1>Chocolates</h1>
<div class="col-md-12 flex flex-center" ng-repeat="chocolate in chocolates">
<div class="col-md-4">
<div class="choco-desc">
<h3 class="capitalize">{{chocolate.type}}</h3>
<p>{{chocolate.description}}</p>
</div>
</div>
<div class="col-md-4">
<div class="choco-desc">
<h3>{{chocolate.price | currency: '$'}}</h3>
</div>
</div>
<div class="col-md-4">
<div class="choco-desc">
<button type="button" name="button" ng-click="addItemToCart(chocolate)">Add To Cart</button>
</div>
</div>
</div>
</div>
<div class="col-md-2">
<button ng-click='toggleModal()'>View Cart ({{getTotalQuantity()}})</button>
<div ng-show="modalShown">
<modal-dialog cart='cart' show="modalShown" close="toggleModal()" width='auto' height='100%'></modal-dialog>
</div>
</div>
</div>
</section>
</div>
</body>
Any guidance is greatly appreciated. Thank you!
Try with this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>

dynamic result counter during search

in this code snippet you can see a little overview which displays some sample data on several table pages. The pagination and everything else works fine but if I type something into my search, the count of the results changes but the counter at the top stays the same. It also should change dynamically if I restrict the results with the search. So for example if I type "item_44" it should display 1 - 1 of 1 because there is just 1 entry.
I would be glad if someone has an idea how to fix the issue.
Here is the working example.
var myApp = angular.module('myApp', []);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
var vm = this;
//vm.currentActive = sessionService.getState();
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.firstItem = 0;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
$scope.numberOfPages = function() {
return Math.ceil($scope.data.length / $scope.pageSize);
}
for (var i = 0; i < 45; i++) {
$scope.data.push("Item " + i);
}
$scope.nextPage = function() {
if ($scope.currentPage >= $scope.data.length / $scope.pageSize - 1) {
} else {
$scope.currentPage = $scope.currentPage + 1;
$scope.firstItem = $scope.firstItem + $scope.pageSize;
if ($scope.firstItem + $scope.pageSize > $scope.data.length) {
$scope.lastItem = $scope.data.length;
} else {
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
$scope.prevPage = function() {
if ($scope.currentPage === 0) {
} else {
$scope.currentPage = $scope.currentPage - 1;
$scope.firstItem = $scope.firstItem - $scope.pageSize;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
.name-row {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div ng-controller="MyCtrl" class="wrapper">
<div class="view-navigation">
<span ng-click="prevPage()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{firstItem +1}} - {{lastItem}} of {{data.length}}</span>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >search</i></span>
<input type="text" ng-model="search" placeholder="search..." />
<table border="1">
<tr>
<th class="name-row">Name</th>
<th class="info-row">Info</th>
</tr>
<tr ng-repeat="item in data | filter:search | startFrom:currentPage*pageSize | limitTo:pageSize">
<td>{{item}}</td>
<td>more info...
</td>
</tr>
</table>
</div>
Somehow the snippet doesn't work in the StackOverflow site.
Try this , its working.
HTML
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div ng-controller="MyCtrl">
<div class="view-navigation">
<span ng-disabled="currentPage == 0" ng-click="back()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{currentPage+1}} - {{numberOfPages()}} von {{getDataLength()}}</span>
<span ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="forward()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span><input type="text" ng-model="q" placeholder="search..."/>
<table border="1">
<tr>
<th>Status</th>
<th>Name</th>
<th>Info</th>
</tr>
<tr ng-repeat="item in s=( data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize)">
<td><span><i class="material-icons" style="color: #8AC65B">check_circle</i></span></td>
<td>{{item}}</td>
<td>more info...</td>
</tr>
</table>
</div>
javascript
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
return $filter('filter')($scope.data, $scope.q)
}
$scope.getDataLength = function () {
var arr = [];
arr = $filter('filter')($scope.data, $scope.q)
return arr.length;
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
$scope.back = function(){
if($scope.currentPage == 0){return}else{
$scope.currentPage=$scope.currentPage-1;}
}
$scope.forward = function(){
var val = $scope.numberOfPages();
if(val == ($scope.currentPage+1)){
alert('val');
}
else {
$scope.currentPage+=1;}
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
}]);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
I am sure Please Change below code according in your code working fine.
var myApp = angular.module('myApp',[]);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
var vm = this;
//vm.currentActive = sessionService.getState();
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.firstItem = 0;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
$scope.numberOfPages=function(){
return Math.ceil($scope.data.length/$scope.pageSize);
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
$scope.nextPage = function(){
if($scope.currentPage >= $scope.data.length/$scope.pageSize - 1){
}
else{
$scope.currentPage = $scope.currentPage + 1;
$scope.firstItem = $scope.firstItem + $scope.pageSize;
if($scope.firstItem + $scope.pageSize > $scope.data.length){
$scope.lastItem = $scope.data.length;
}
else{
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
$scope.prevPage = function(){
if($scope.currentPage === 0){
}
else{
$scope.currentPage = $scope.currentPage - 1;
$scope.firstItem = $scope.firstItem - $scope.pageSize;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
<html ng-app='myApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head><body ng-controller="MyCtrl" >
<div class="wrapper">
<div class="view-navigation">
<span ng-click="prevPage()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{firstItem +1}} - {{griddata.length}} of {{data.length}}</span>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span><i class="material-icons" >search</i></span><input type="text" ng-model="search" placeholder="search..."/>
<table border="1">
<tr>
<th class="name-row">Name</th>
<th class="info-row">Info</th>
</tr>
<tr ng-repeat="item in griddata=(data | filter:search | startFrom:currentPage*pageSize | limitTo:pageSize)">
<td>{{item}}</td>
<td>more info...</td>
</tr>
</table>
</div>
</body>
</html>

Angular JS indefinite execution of a function called inside a ng-repeat

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.

10 is evaluating to 1 in array

Whenever the user picks 10 in the dropdown (either formData.minRating or formData.maxRating)in main.html it evaluates to 1. I found this out by testing how the ng-change in main.html evaluates. If I pick the formData.maxRating to be 10 and then formData.minRating to be 2, it will say that the minRating is larger than the maxRating which isn't true. But when I do console.log's for all of the variables, it says they're the correct values. So I don't know what's wrong. How do I get the 10 to evaluate to 10 and not 1?
main.html
<div layout="column" layout-align="center">
<div>
<md-input-container>
<md-label>Set Genre</md-label>
<md-select ng-model="formData.selectedGenre" ng-change="setGenreId(formData.selectedGenre)" placeholder="Genre">
<md-option ng-repeat="genre in genreList" value="{{genre.id}}">{{genre.name}}</md-option>
</md-select>
</md-input-container>
</div>
<div>
<md-input-container>
<md-label>Set Min Rating</md-label>
<p style="color:red" ng-show="formData.minRating > formData.maxRating"> Min rating cannot be larger than max rating</p>
<md-select ng-model="formData.minRating" ng-change="setMinRating(formData.minRating)">
<md-option ng-repeat="num in [1,2,3,4,5,6,7,8,9,10]" value="{{num}}">{{num}}</md-option>
</md-select>
</md-input-container>
</div>
<div>
<md-input-container>
<md-label>Set Max Rating</md-label>
<md-select ng-model="formData.maxRating" ng-change="setMaxRating(formData.maxRating)">
<md-option ng-repeat="num in [1,2,3,4,5,6,7,8,9,10]" value="{{num}}">{{num}}</md-option>
</md-select>
</md-input-container>
</div>
<div>
<md-button class="md-raised md-primary" ng-disabled="formData.minRating >= formData.maxRating">Submit</md-button>
</div>
</div>
main.js
angular.module('pickMeAmovieApp')
.controller('MainCtrl',function ($scope,movieFactory,sharedProperties) {
$scope.genreList = [];
getGenres();
$scope.values = [1,2,3,4,5,6,7,8,9,11];
$scope.formData = {};
$scope.formData.minRating = sharedProperties.getMinRating();
$scope.formData.maxRating = sharedProperties.getMaxRating();
function getGenres(){
movieFactory.getGenres().then(function(response){
$scope.genres = response['genres'];
angular.forEach($scope.genres, function(value) {
$scope.genreList.push(value);
});
});
};
$scope.setGenreId = function (genreId){
sharedProperties.setGenreId(genreId);
console.log(sharedProperties.getGenreId());
};
$scope.setMaxRating = function (rating){
sharedProperties.setMaxRating(rating);
//$scope.maxRating = sharedProperties.getMaxRating();
console.log("max: " + $scope.formData.maxRating);
console.log("min: " + $scope.formData.minRating);
};
$scope.setMinRating = function (rating){
sharedProperties.setMinRating(rating);
//$scope.minRating = sharedProperties.getMinRating();
console.log("min: " + $scope.formData.minRating);
console.log("max: " + $scope.formData.maxRating);
};
});
sharedProperties.js
angular.module('pickMeAmovieApp')
.service('sharedProperties', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
var _genreId = null;
var _minRating = 1;
var _maxRating = 10;
this.getGenreId = function () {
return _genreId;
};
this.setGenreId = function(value) {
_genreId = value;
};
this.getMinRating = function() {
return _minRating;
};
this.setMinRating = function(rating){
_minRating = rating;
};
this.getMaxRating = function(){
return _maxRating;
};
this.setMaxRating = function(rating){
_maxRating = rating;
};
});
Angular is treating each of the values as strings
you can check by using typeof formData.maxRating
In your JS, write:
$scope.parseInt = function(i) {
return parseInt(i);
};
In your HTML, use:
<div>
<md-button class="md-raised md-primary" ng-disabled="parseInt(formData.minRating) >= parseInt(formData.maxRating)">Submit</md-button>
</div>

Categories

Resources