Getting Uncaught Error: [$injector:modulerr] - javascript

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>

Related

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

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

My ng-click is not firing

I'm new to Angular, so please bear with me.
I have an app I'm building where you can hit an "X" or a heart to dislike/like something. I'm using a swipe library called ng-swippy.
I'm trying to use ng-click="clickLike()"for the "Like" button and ng-click="clickDislike()"but neither are firing. I can't figure out what's going on.
Here's the URL:
http://430designs.com/xperience/black-label-app/deck.php
deck.php code
<ng-swippy collection='deck' item-click='myCustomFunction'
data='showinfo' collection-empty='swipeend' swipe-left='swipeLeft'
swipe-right='swipeRight' cards-number='4' label-ok='Cool'
label-negative='Bad'>
</ng-swippy>
The template is called from card-tpl.html:
<div class="ng-swippy noselect">
<div person="person" swipe-directive="swipe-directive" ng-repeat="person in peopleToShow" class="content-wrapper swipable-card">
<div class="card">
<div style="background: url({{person.thumbnail}}) no-repeat 50% 15%" class="photo-item"></div>
<div class="know-label">{{labelOk ? labelOk : "YES"}}</div>
<div class="dontknow-label">{{labelNegative ? labelNegative : "NO"}}</div>
</div>
<div class="progress-stats" ng-if="data">
<div class="card-shown">
<div class="card-shown-text">{{person.collection}}</div>
<div class="card-shown-number">{{person.subtitle}}</div>
</div>
<div class="card-number">{{collection.length - (collection.indexOf(person))}}/{{collection.length}}
</div>
</div>
<div class="container like-dislike" >
<div class="circle x" ng-click="clickDisike()"></div>
<div class="icon-like" ng-click="clickLike()"></div>
<div class="clearfix"></div>
</div>
</div><!-- end person-->
<div class="clearfix"></div>
Controller.js
angular.module('black-label', ['ngTouch', 'ngSwippy'])
.controller('MainController', function($scope, $timeout, $window) {
$scope.cardsCollection = [
{
thumbnail: 'images/deck/thor_01.jpg',
collection: 'thoroughbred',
}, {
thumbnail: 'images/deck/thor_02.jpg',
collection: 'thoroughbred',
},
];
// Do the shuffle
var shuffleArray = function(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
$scope.deck = shuffleArray($scope.cardsCollection);
$scope.myCustomFunction = function(person) {
$timeout(function() {
$scope.clickedTimes = $scope.clickedTimes + 1;
$scope.actions.unshift({ name: 'Click on item' });
$scope.swipeRight(person);
});
};
$scope.clickLike = function(person) {
console.log($scope.count);
// swipeRight(person);
};
$scope.count = 0;
$scope.showinfo = false;
$scope.clickedTimes = 0;
$scope.actions = [];
$scope.picks = [];
var counterRight = 0;
var counterLeft = 0;
var swipes = {};
var picks = [];
var counts = [];
var $this = this;
$scope.swipeend = function() {
$scope.actions.unshift({ name: 'Collection Empty' });
$window.location.href = 'theme-default.html';
};
$scope.swipeLeft = function(person) {
//Essentially do nothing
$scope.actions.unshift({ name: 'Left swipe' });
$('.circle.x').addClass('dislike');
$('.circle.x').removeClass('dislike');
$(this).each(function() {
return counterLeft++;
});
};
$scope.swipeRight = function(person) {
$scope.actions.unshift({ name: 'Right swipe' });
// Count the number of right swipes
$(this).each(function() {
return counterRight++;
});
// Checking the circles
$('.circle').each(function() {
if (!$(this).hasClass('checked')) {
$(this).addClass('checked');
return false;
}
});
$('.icon-like').addClass('liked');
$('.icon-like').removeClass('liked');
$scope.picks.push(person.collection);
// console.log('Picks: ' + $scope.picks);
// console.log("Counter: " + counterRight);
if (counterRight === 4) {
// Calculate and store the frequency of each swipe
var frequency = $scope.picks.reduce(function(frequency, swipe) {
var sofar = frequency[swipe];
if (!sofar) {
frequency[swipe] = 1;
} else {
frequency[swipe] = frequency[swipe] + 1;
}
return frequency;
}, {});
var max = Math.max.apply(null, Object.values(frequency)); // most frequent
// find key for the most frequent value
var winner = Object.keys(frequency).find(element => frequency[element] == max);
$window.location.href = 'theme-' + winner + '.html';
} //end 4 swipes
}; //end swipeRight
});
Any thoughts and help is greatly appreciated!
The ng-click directive is inside an ng-repeat directive inside a directive with isolate scope. To find the clickLike() function it needs to go up two parents:
<!--
<div class="icon-like" ng-click="clickLike()"></div>
-->
<div class="icon-like" ng-click="$parent.$parent.clickLike()"></div>
For information, see AngularJS Wiki - Understanding Scopes.

Angular : Display data item stored in an array one by one

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){

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.

Why $scope.variable in ChildController is not resolving to the $scope.variable in ParentController

Why in this jsfiddle $scope.counter inside ChildController3 do not resolve to ParenctController's $scope.counter but creates a counter on local $scope?
Replicating Code:
HTML
<div ng-app='app'>
<div ng-controller="ParentController">
<h2>ChildController1</h2>
<div ng-controller="ChildController1">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
</div>
<h2>ChildController2</h2>
<div ng-controller="ChildController2">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
<br/>
{{ counter }} <- this is in local scope
</div>
{{ counter }} <- this is in parent scope
<h2>ChildController3</h2>
<div ng-controller="ChildController3">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
<br/>
{{ counter }} <- this is in local scope
</div>
</div>
</div>
JS
var app = angular.module("app",[]);
app.controller('ParentController', function($scope)
{
$scope.counter = 5;
});
app.controller('ChildController1', function ($scope) {
$scope.add = function () {
$scope.counter += 1;
};
$scope.subtract = function () {
$scope.counter -= 1;
};
});
app.controller('ChildController2',function($scope) {
$scope.add = function () {
$scope.$parent.counter += 1;
};
$scope.subtract = function () {
$scope.$parent.counter -= 1;
};
});
app.controller('ChildController3', function($scope) {
$scope.add = function () {
$scope.counter += 1;
};
$scope.subtract = function () {
$scope.counter -= 1;
};
});
Its because the scopes of different levels in the hierarchy share scope using prototypical inheritance.
A pure JS example would be:
function A(){
this.count = 5;
}
function B(){
}
a = new A();
B.prototype = a;
b = new B();
console.log(a.count,b.count); // gives 5 5 <--- shared
a.count++;
console.log(a.count,b.count); // give 6 6 <----- still shared
b.count++;
console.log(a.count,b.count); // gives 6 7 <----- link broken
a.count++;
The link is broken because after "b.count++;" b really has a count property, before that it was just a prototype property.
More info on this can be found here: Angular scope docs
try this:
<div ng-app='app'>
<div ng-controller="ParentController">
<h2>ChildController1</h2>
<div ng-controller="ChildController1">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
</div>
<h2>ChildController2</h2>
<div ng-controller="ChildController2">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
<br/>
{{ number.counter }} <- this is in local scope
</div>
{{ number.counter }} <- this is in parent scope
<h2>ChildController3</h2>
<div ng-controller="ChildController3">
<button ng-click="add()">Add</button>
<button ng-click="subtract()">Subtract</button>
<br/>
{{ number.counter }} <- this is in local scope
</div>
</div>
</div>
var app = angular.module("app",[]);
app.controller('ParentController', function($scope)
{
$scope.number = {};
$scope.number.counter = 5;
});
app.controller('ChildController1', function ($scope) {
$scope.add = function () {
$scope.number.counter += 1;
};
$scope.subtract = function () {
$scope.number.counter -= 1;
};
});
app.controller('ChildController2',function($scope) {
$scope.add = function () {
$scope.$parent.number.counter += 1;
};
$scope.subtract = function () {
$scope.$parent.number.counter -= 1;
};
});
app.controller('ChildController3', function($scope) {
$scope.add = function () {
$scope.number.counter += 1;
};
$scope.subtract = function () {
$scope.number.counter -= 1;
};
});
This happens because you´re overwriting your $scope.counter inside 'ChildController3'.
here, see this video at 30 min to see a better explanation about this:
AngularJS MTV Meetup: Best Practices
What happened here to make it work was because you declared "$scope.number = {};" inside "ParentController", so when you use it "$scope.number.counter" inside "ChildController3" you made a reference to ParentController instead of before when you just overwrote "$scope.counter" inside of "ChildController3".

Categories

Resources