input value returns NaN on ng-click - javascript

I am writing a program that takes in input value for two numbers and provides a random value from the range specified. I have fixed controllers to shuffle min and max value and it works once i place numbers but if i add the ng-model value, it returns "NaN". Here is the html
<div class="col-sm-4" ng-controller="ValueController">
<div class="row">
<div class="col-sm-6"><input type="number" ng-model="value.one">
</div>
<div class="col-sm-6"><input ng-model="value.two"></div>
</div>
</div>
<div class="col-sm-4">
<a ng-href="results.html" ng-controller="ShuffleController"
ng-click="shuffle(100100, 110000)">
<img src="img/before.png" style="width: 500px; height: auto;"></a>
</ul>
</div>
Here is part of the app.js:
// Angular App Initialization
var app = angular.module('Shuffle', ['ngRoute']);
// Declaring Globals
app.run(function($rootScope) {
$rootScope.shuffled = [];
$rootScope.shuffleValues = {};
$rootScope.getRand = function(min, max) {
var number = Math.floor(Math.random() * (max - min)) + min;
var leadingZeroes = 6 - number.toString().length;
$rootScope.shuffled.push([[min, max], number.toString().length < 6 ? ('0'.repeat(leadingZeroes) + number) : number]);
window.localStorage.setItem('shuffled', JSON.stringify($rootScope.shuffled));
}
});
// Shuffle Controller
app.controller('ShuffleController', function($scope, $rootScope, $window) {
console.log('Welcome to TheShuffler!');
var results = window.localStorage.getItem('shuffled');
results = JSON.parse(results);
$scope.shuffle = function(min, max) {
console.log("You shuffled!");
console.log(results);
$rootScope.getRand(min, max);
}
});
// Results Controller
app.controller('ResultsController', function($scope) {
var results = window.localStorage.getItem('shuffled');
$scope.shuffleResults = JSON.parse(results);
$scope.quantity = 3;
console.log($scope.shuffleResults);
});
// Reshuffling Controller
app.controller('ReshuffleController', function($scope, $rootScope, $route, $window, $location) {
$scope.reshuffle = function(){
$window.location.reload();
console.log('You reshuffled!');
var results = window.localStorage.getItem('shuffled');
results = $scope.shuffleResults = JSON.parse(results);
for (var i = 0; i < results.length; i++) {
var min = results[i][0][0]
var max = results[i][0][1]
$rootScope.getRand(min, max)
}
}
});
// Shuffle Entries Verification Controller
app.controller('ShuffleEntriesVerificationController', function($scope, $window) {
console.log('EntriesHere!');
$scope.entryCheck = function(){
var results = window.localStorage.getItem('shuffled');
results = JSON.parse(results);
console.log("You checked!");
console.log(results);
var verficationMessage = "Maximum Entries Exceeded. Please Click Shuffle";
if (results.length > 2) {
$window.alert(verficationMessage);
$window.location.reload();
}
}
});
app.controller('ValueController', ['$scope', function($scope) {
$scope.value = {
one: 000100,
two: 005100
};
}]);
it('should check ng-bind', function() {
var nameInput = element(by.model('value'));
expect(element(by.binding('value')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('value')).getText()).toBe('world');
});
I get NaN when i do this:
<a ng-href="results.html" ng-controller="ShuffleController"
ng-click="shuffle(value.one, value.two)">
<img src="img/before.png" style="width: 500px; height: auto;"></a>
What is the problem?

You have a wrong controller:
ng-controller="ShuffleController"
while in your app you have this controller:
app.controller('ValueController',...
...
}]);

You don't have to pass the model as parameter values will be automatically bound and available in your shuffle function.
In case of your NaN error create a snippet to get a better perspective of your problem

Related

AngularJS 1.6 application bug: turning items pagination into a service does not work

I am making a small Contacts application with Bootstrap 4 and AngularJS v1.6.6.
The application simply displays an Users JSON. Since the JSON returns a large number of users, the application also has a pagination feature.
The pagination worked fine as part of the app's controller, but since I tried to turn it into a service, it does not work anymore.
See a functional version of the application, with the pagination inside the controller HERE.
The application controller:
// Create an Angular module named "contactsApp"
var app = angular.module("contactsApp", []);
// Create controller for the "contactsApp" module
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
var url = "https://randomuser.me/api/?&results=100&inc=name,location,email,cell,picture";
$scope.contactList = [];
$scope.search = "";
$scope.filterList = function() {
var oldList = $scope.contactList || [];
$scope.contactList = $filter('filter')($scope.contacts, $scope.search);
if (oldList.length != $scope.contactList.length) {
$scope.pageNum = 1;
$scope.startAt = 0;
};
$scope.itemsCount = $scope.contactList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
$http.get(url)
.then(function(data) {
// contacts arary
$scope.contacts = data.data.results;
$scope.filterList();
// Pagination Service
$scope.paginateContacts = function(){
$scope.pagination = paginationService.paginateContacts();
}
});
}]);
The service:
app.factory('paginationService', function(){
return {
paginateContacts: function(){
// Paginate
$scope.pageNum = 1;
$scope.perPage = 24;
$scope.startAt = 0;
$scope.filterList();
$scope.currentPage = function(index) {
$scope.pageNum = index + 1;
$scope.startAt = index * $scope.perPage;
};
$scope.prevPage = function() {
if ($scope.pageNum > 1) {
$scope.pageNum = $scope.pageNum - 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
$scope.nextPage = function() {
if ($scope.pageNum < $scope.pageMax) {
$scope.pageNum = $scope.pageNum + 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
}
}
});
In the view:
<div ng-if="pageMax > 1">
<ul class="pagination pagination-sm justify-content-center">
<li class="page-item"><i class="fa fa-chevron-left"></i></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index" ng-class="{true: 'active'}[$index == pageNum - 1]">
{{$index+1}}
</li>
<li><i class="fa fa-chevron-right"></i></li>
</ul>
</div>
The service file is included in the project (correctly, in my opinion) after the app.js file:
<script src="js/app.js"></script>
<script src="js/paginationService.js"></script>
I am not an advanced AngularJS user so I don't know: what is missing?
It appears that the service needs to be defined before the controller, otherwise it cannot be injected properly.
So you could either move the paginationService into app.js:
var app = angular.module("contactsApp", []);
app.factory('paginationService', function(){
//...
});
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
//...
});
Or else move the controller out to a separate file that is included after the paginationServices.js file.
Take a look at this plunker. Try modifying line 6 - remove character 5, i.e. the space that separates the star and slash that would close the multi-line comment.

Compare two last character in a string

I am programming a calculator in AngularJS. I am stuck on a validating user input. I do not want the user to be able to enter two 2 operators ('+','/','*') next to each other.
Thus every time, I try to compare the last character and the second to last character of the string. But I always find I have two operator characters.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.expression = "";
var liste = ['+', '/', '*'];
$scope.add = function (ope) {
$scope.expression += String(ope);
var der = $scope.expression[$scope.expression.length - 1];
var avantDer = $scope.expression[$scope.expression.length - 2];
if ($scope.expression.length > 3 && liste.includes(der) && liste.includes(avantDer)) {
alert("error");
} else {
$scope.expression += String(ope);
}
};
});
You are very close. The problem is that you are adding the operator to the expression before you have checked if it is valid or not. It is better to check the last character of the existing expression and the new character as a separate variable.
You also want to check if the length of expression is greater than 0 rather than 3 as otherwise, the user could enter two '+' characters straight away when the length is less than 3.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.expression = "";
var liste = ['+', '/', '*'];
$scope.add = function (ope) {
// don't add to expression, just store into der
var der = String(ope);
var avantDer = $scope.expression[$scope.expression.length - 1];
if ($scope.expression.length > 0 && liste.includes(der) && liste.includes(avantDer)) {
alert("error");
} else {
$scope.expression += der;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<button ng-click="add('+')">+</button>
<button ng-click="add('*')">*</button>
<button ng-click="add('/')">/</button>
</div>
<div>
<button ng-click="add('1')">1</button>
<button ng-click="add('2')">2</button>
<button ng-click="add('3')">3</button>
</div>
{{expression}}
</div>
There were two things wrong.
$scope.expression.length > 3 should have been
$scope.expression.length > 2
You were calling $scope.expression += String(ope); twice
I made a minor change below so I could run it in the code snippet window.
I also added subtraction to liste.
var $scope = {
expression: ""
};
var liste = ['+', '/', '*', '-'];
debugger
$scope.add = function (ope) {
var temp = $scope.expression + String(ope);
console.log(temp);
var len = temp.length - 1;
if (len > 1) {
var der = temp[len];
var avantDer = temp[len - 1];
if (liste.includes(der) && liste.includes(avantDer)) {
console.log("error");
} else {
$scope.expression = temp;
}
}
else {
$scope.expression = temp;
}
};
$scope.add('3');
$scope.add('+');
$scope.add('-');
When I call $scope.add('-'); it displays the error like you expect.

Angularjs displaying a calculated value depending on true/false flags

I'm facing a need to display a sum of values (related to $scope variables) depending on the selection of flags. For instance:
There are 4 $scope variables (e.g. $scope.Var_1, $scope.Var_2...) containing integer values,
There are 4 $scope variables (e.g. $scope.Var_1_Flag, $scope.Var_2_Flag...)containing true or false for each of the above integer variables.
So, in we have:
$scope.Var_1 = 1 ;
$scope.Var_2 = 2 ;
$scope.Var_3 = 3 ;
$scope.Var_4 = 4 ;
$scope.Var_1_Flag = true ;
$scope.Var_2_Flag = true ;
$scope.Var_3_Flag = true ;
$scope.Var_4_Flag = true ;
then 10 will be displayed, but if:
$scope.Var_1_Flag = true ;
$scope.Var_2_Flag = false;
$scope.Var_3_Flag = false;
$scope.Var_4_Flag = true ;
then 5 will be displayed.
Does AngularJS supports a binding syntax that would realize this?
Thanks.
MARKUP:
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="Var_1_Flag" ng-checked="Var_1_Flag" ng-change="changeStatus(Var_1_Flag);" />
<input type="checkbox" ng-model="Var_2_Flag" ng-checked="Var_2_Flag" ng-change="changeStatus(Var_2_Flag);" />
<input type="checkbox" ng-model="Var_3_Flag" ng-checked="Var_3_Flag" ng-change="changeStatus(Var_3_Flag);" />
<input type="checkbox" ng-model="Var_4_Flag" ng-checked="Var_4_Flag" ng-change="changeStatus(Var_4_Flag);" />
<br/> Sum is: {{sum}}
</div>
JS:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.sum = 0;
$scope.Var_1 = 1;
$scope.Var_2 = 2;
$scope.Var_3 = 3;
$scope.Var_4 = 4;
$scope.Var_1_Flag = true;
$scope.Var_2_Flag = false;
$scope.Var_3_Flag = false;
$scope.Var_4_Flag = true;
$scope.changeStatus = function(checkValue) {
$scope.checkValue = !checkValue;
$scope.calculateSum();
}
$scope.calculateSum = function() {
$scope.sum = ($scope.Var_1_Flag ? $scope.Var_1 : 0) + ($scope.Var_2_Flag ? $scope.Var_2 : 0) + ($scope.Var_3_Flag ? $scope.Var_3 : 0) + ($scope.Var_4_Flag ? $scope.Var_4 : 0)
}
$scope.calculateSum();
}
Check this http://jsfiddle.net/ananyaojha/ADukg/13641/
// Need to keep track of watcher
$scope.$watch('Var_1_Flag', function(newVal, oldVal){
// this callback is invoked if any change is detected in the value of Var_1_Flag
// add condition and update scope using $apply or $evalAsync
// You have to set watchers also whenever flags are keep getting changed for all falg types.
})
you will have to watch the scope variables
$scope.$watch('Var_1_Flag', function(newVal, oldVal){
// this callback is invoked if any change is detected in the value of Var_1_Flag
// add condition and update scope using $apply or $evalAsync
})
you could set up more watchers or add all the flag variables into a object and then watch the object so you don't have to use a different callback for each scope variable
Create an Array of Objects with value and flag propeties. And create filter to check the flag and sum of only those values.
$scope.sumArray = [
{value:1,flag:true},
{value:2,flag:false},
{value:3,flag:false},
{value:4,flag:true}
];
You could instead assign the function the the $scope.variable..makes it more easier..hope this is what you are looking for
angular.module('myApp', [])
.controller('MainCtrl', function($scope) {
$scope.Var_1_Flag = true;
$scope.Var_2_Flag = false;
$scope.Var_3_Flag = true;
$scope.Var_4_Flag = true;
$scope.var_1 = function() {
if ($scope.Var_1_Flag) {
return 1;
} else {
return 0;
}
}
$scope.var_2 = function() {
if ($scope.Var_2_Flag) {
return 2;
} else {
return 0;
}
}
});
<body ng-app="myApp" ng-controller="MainCtrl">
<div>
<span>{{var_1() + var_2()}} </span>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
In your controller :
$scope.sumValues =0;
var Values =[
{v:1,f:true},
{v:2,f:false},
{v:3,f:false},
{v:4,f:true}];
Values.forEach(function(element) {
if(element.f)
$scope.sumValues += element.v;
});
and in your HTML :
<div ng-controller="MyCtrl">
{{sumValues}}
</div>
I create an example for you :
http://jsfiddle.net/ADukg/13643/
$scope.sumArray = [
{value:1,flag:true},
{value:2,flag:false},
{value:3,flag:false},
{value:4,flag:true}
];
function sum(){
$scope.sum =0;
for(var i=0;i<$scope.sumArray.length;i++){
$scope.sum = $scope.sum +
$scope.sumArray[i].flag ? $scope.sumArray[i].value: 0
}
}
$scope.$watch('$scope.sumArray', sum,true);
or :
you can use $filter
function sum(){
$scope.sum=0;
var filtered = $filter('filter')($scope.sumArray,'flag');
for(var i=0;i<filtered.length;i++){
$scope.sum = $scope.sum+filtered[i].value;
}
}
You just need One $watch to update the values of sum. Watch all the flags together and whenever the checkbox(flag) changes, the sum will automatically update.
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller("MyCtrl", function($scope) {
$scope.sum = 0;
$scope.Var_1 = 1;
$scope.Var_2 = 2;
$scope.Var_3 = 3;
$scope.Var_4 = 4;
$scope.Var_1_Flag = true;
$scope.Var_2_Flag = false;
$scope.Var_3_Flag = false;
$scope.Var_4_Flag = true;
$scope.$watch('Var_1_Flag + Var_2_Flag + Var_3_Flag +Var_4_Flag', function(val) {
$scope.sum = ($scope.Var_1_Flag ? $scope.Var_1 : 0) + ($scope.Var_2_Flag ? $scope.Var_2 :
0) + ($scope.Var_3_Flag ? $scope.Var_3 : 0) + ($scope.Var_4_Flag ? $scope.Var_4 :
0);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<h6>
CheckBoxes
</h6>
<input type="checkbox" ng-model="Var_1_Flag">
<input type="checkbox" ng-model="Var_2_Flag">
<input type="checkbox" ng-model="Var_3_Flag">
<input type="checkbox" ng-model="Var_4_Flag">
<h6>
Sum
</h6> {{sum}}
</div>
I found an amazingly simple solution that does the job exactly as I wanted.
Here is a piece of code within the controller:
$scope.Test_1_Value = 1 ;
$scope.Test_1_Flag = true ;
$scope.Test_2_Value = 2 ;
$scope.Test_2_Flag = true ;
$scope.Test_3_Value = 3 ;
$scope.Test_3_Flag = true ;
$scope.Test_4_Value = 4 ;
$scope.Test_4_Flag = true ;
$scope.ConditionalAdd = function (p1,p2,p3,p4) {
var aaa = 0 ;
if ($scope.Test_1_Flag) {aaa = aaa + $scope.Test_1_Value }
if ($scope.Test_2_Flag) {aaa = aaa + $scope.Test_2_Value }
if ($scope.Test_3_Flag) {aaa = aaa + $scope.Test_3_Value }
if ($scope.Test_4_Flag) {aaa = aaa + $scope.Test_4_Value }
return aaa ;
}
and here the HTML part:
<input type="checkbox" ng-model="Test_1_Flag"> Add 1
<br>
<input type="checkbox" ng-model="Test_2_Flag"> Add 2
<br>
<input type="checkbox" ng-model="Test_3_Flag"> Add 3
<br>
<input type="checkbox" ng-model="Test_4_Flag"> Add 4
<br>
<label>Total 1: </label> {{ConditionalAdd(Test_1_Value,Test_2_Value,Test_3_Value,Test_4_Value)}}
As the checkboxes are changed (checked/unchecked), the result shown next to Total 1: is updated automatically, as needed.
The values Test_x_Value are part of the data generated for the creation and population of the table (using ng-repeat), and hence are available within each single cell of the table.
So, no filters, no watches.
Thanks to every one for your support :-).
EDIT:
I just finished implementing this solution and tested it with a table containing over 2,500 cells. This solution works perfectly well, including performance.

how to change image dynamically according to the values in angular js

i want to show particular image when value is greater than 3(float) . while less than 3 it should show different image. how to write condition in of comparing value and according to that need to show.
condition
value > 3.5 = http://icons.iconarchive.com/icons/custom-icon-design/flatastic-9/256/Accept-icon.png
value =< http://icons.iconarchive.com/icons/custom-icon-design/flatastic-9/256/Accept-icon.png
code
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http.get('https://example.com/get', {
headers: { 'Authorization': 'Basic a2VybmVsc==' }
})
.then(function (response) {
$scope.names = response.data;
$scope.decodedFrame = atob($scope.names.dataFrame);
$scope.decodedFrameNew = $scope.decodedFrame.substring(4);
$scope.distanceinFeet = 835 * 0.95;
$scope.Value = $scope.distanceinFeet / 148;
$scope.parkingslot1 = $scope.Value.toFixed(2);
$scope.names.timestamp = new Date($scope.names.timestamp).toLocaleString(); // Parse the date to a localized string
});
alert("hi");
$scope.getSlotImage = function (slot) {
alert("hi");
var imageUrl = slot > 3.5 ? 'http://icons.iconarchive.com/icons/custom-icon-design/flatastic-9/256/Accept-icon.png' :
'https://cdn3.iconfinder.com/data/icons/musthave/256/Cancel.png'
alert("hi");
return imageUrl;
alert("hi");
}
});
</script>
body
<td><img ng-if ng-src="{{getSlotImage(parkingslot1)}}" /></td>
You could just call a function inside ng-src to get the relevant image.
Below you can see, how it should look like your controller and view
View
No need ng-if here.
<td><img ng-src="{{getSlotImage(parkingslot1)}}" /></td>
Controller
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get('https://example.com/get', {
headers: {
'Authorization': 'Basic a2VybmVsc=='
}
})
.then(function(response) {
$scope.names = response.data;
$scope.decodedFrame = atob($scope.names.dataFrame);
$scope.decodedFrameNew = $scope.decodedFrame.substring(4);
$scope.distanceinFeet = 835 * 0.95;
$scope.Value = $scope.distanceinFeet / 148;
$scope.parkingslot1 = $scope.Value.toFixed(2);
$scope.names.timestamp = new Date($scope.names.timestamp).toLocaleString(); // Parse the date to a localized string
});
$scope.getSlotImage = function(slot) {
var imageUrl = slot > 3.5 ? 'http://icons.iconarchive.com/icons/custom-icon-design/flatastic-9/256/Accept-icon.png' : 'https://cdn3.iconfinder.com/data/icons/musthave/256/Cancel.png';
return imageUrl;
}
});
Try this
<img ng-if="Value>3.5" ng-src="{{slot1image['>3.5']}}" /></td>
<img ng-if="Value<=3.5" ng-src="{{slot1image['<=3.5']}}" /></td>
Unfortunatly you can not use dot notation

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.

Categories

Resources