angularjs dynamically creating an array of string and then comparing it - angularjs

I am building an Ionic application which looks as follows: http://plnkr.co/edit/eYKQPM?p=preview
The flow of the application is as follows:
User clicks 'Start' button and then a timer of 5 seconds starts (user should remember all the pairs). After 5 seconds are over, in the next 20 seconds user is supposed to fill the corresponding pair in front of the word. Feedback is given with a tick-mark if he fills in correct pair
If the user is finished filling up the correct pairs he can click 'Stop'button.
TODO: I have an array of all the pairs from $scope.expectedSequence however I do not know how can I build array $scope.enteredSequence, and then check them in $scope.checkCorrectness function to make progression or play the same level. As of now I have there a dummy check to make progression. It ideally should check something like:
if(angular.equals($scope.expectedSequence,$scope.enteredSequence)){...}
My controller:
.controller('DashCtrl', function($scope, $timeout) {
$scope.level=1
$scope.leftList=false
$scope.enterTextView=false
$scope.previewView=false
$scope.promptAction=''
$scope.promptLevel=''
$scope.enteredSequence=[]
$scope.expectedSequece=[]
$scope.show_stop_button=false
$scope.show_start_button=true
$scope.word_pair = [
{'word':'Nitish', 'pair':'Patkar'},
{'word':'Mihir', 'pair':'Janaj'},
{'word':'Jannes', 'pair':'Stubbi'},
{'word':'Martin', 'pair':'Wolle'}
]
$scope.partnerCheckList = {};
for(var v in $scope.word_pair){
$scope.expectedSequece.push($scope.word_pair[v].pair)
console.log($scope.expectedSequece)
$scope.partnerCheckList[$scope.word_pair[v].word] = $scope.word_pair[v].pair;
}
$scope.showPartner = {};
$scope.partnerCheck = function(p,i_p){
if($scope.partnerCheckList[i_p] == p){
$scope.showPartner[p] = true;
}
}
$scope.start = function(){
$scope.show_start_button=false
$scope.leftList=true
$scope.previewView=true
$scope.promptLevel='Level: ' + $scope.level
$scope.counter1=5
$timeout($scope.startFilling, 5000)
$scope.onTimeout = function(){
$scope.counter1--;
mytimeout = $timeout($scope.onTimeout,1000);
if($scope.counter1==0){
$timeout.cancel(mytimeout);
}
}
var mytimeout = $timeout($scope.onTimeout,1000);
}
$scope.startFilling = function(){
$scope.promptLevel='Level: ' + $scope.level
$scope.promptAction='Now enter the corresponding pairs in the right column'
$scope.enterTextView=true
$scope.previewView=false
$scope.show_start_button=false
$scope.show_stop_button=true
$scope.counter2=20
$timeout($scope.checkCorrectness, 20000)
$scope.onTimeout = function(){
$scope.counter2--;
mytimeout = $timeout($scope.onTimeout,1000);
if($scope.counter2==0){
$timeout.cancel(mytimeout);
$scope.enterTextView=false
$scope.previewView=false
$scope.leftList=false
$scope.show_stop_button=false
$scope.show_start_button=true
}
}
var mytimeout = $timeout($scope.onTimeout,1000);
}
$scope.checkCorrectness = function(){
$scope.ok=true
$scope.enterTextView=false
$scope.previewView=true
$scope.promptAction=''
$scope.promptLevel=''
/*dummy check*/
if($scope.ok){
$scope.level= $scope.level + 1
$scope.promptLevel='Level: ' + $scope.level
}
}
})
Mt HTML:
<ion-view view-title="Dashboard">
<ion-content class="padding">
<div align="center" ng-if="promptLevel">
<h3>{{promptLevel}}</h3>
</div>
<div align="center" ng-if="promptAction">
<h3>{{promptAction}}</h3>
</div>
<div align="center" ng-if="counter1">
<h3>{{counter1}}</h3>
</div>
<div align="center" ng-if="counter2">
<h3>{{counter2}}</h3>
</div>
<div class="row">
<!-- Left half of the screen to hold list of words -->
<div class="col col-50" align="center" style="padding-top:0.2cm;" ng-if="leftList">
<ion-list>
<ion-item ng-repeat="item in word_pair" id="list_one">
<h2>{{item.word}}</h2>
</ion-item>
</ion-list>
</div>
<!-- Right half of the screen to hold list of pairs -->
<div class="col col-50" ng-if="previewView">
<ion-list>
<ion-item ng-repeat="item in word_pair" id="list_two">
<h2>{{item.pair}}</h2>
</ion-item>
</ion-list>
</div>
<div class="col col-50" ng-if="enterTextView">
<ion-list>
<ion-item ng-repeat="item in word_pair" id="list_two">
<input ng-model="pair" type="text" ng-change="partnerCheck(pair,item.word)">
<div ng-show="showPartner[pair]" align="right"><i class="ion-checkmark myCheckmark"></i></div>
</ion-item>
</ion-list>
</div>
</div>
<div align="center" style="padding-bottom:1cm;" ng-if="show_start_button">
<button class="button button-dark start-button" ng-click="start()">Start</button>
</div>
<div align="center" ng-if="show_stop_button">
<button class="button button-dark start-button" >Stop</button>
</div>
</ion-content>
</ion-view>

With following code modification I was able to get correct $scope.entereddSequence
$scope.partnerCheck = function(p,i_p){
if($scope.partnerCheckList[i_p] == p){
$scope.showPartner[p] = true;
$scope.enteredSequence.push(p)
}
}

Related

Add change amount and change the Total in Check Box in Ionic

I created a list in Checkbox, listing products where the user can choose a product. I need add in the product list an option where the user can change the quantity of products selected. How I can do it?
My View:
<ion-view view-title="Bebidas Adicionais" ng-controller="exBebidasCtrl" >
<div class="bar bar-subheader">
<h2 class="title">{{'Sub-Total R$ ' + getTotalSelected()}}</h2>
</div>
<ion-refresher pulling-text="Puxe para atualizar..." on-refresh="doRefresh()"></ion-refresher>
<ion-list class="card list">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="q" placeholder="Procurar" aria-label="filter bebidasextras" />
</div>
</ion-list>
<ion-list>
<div ng-repeat="bebida in bebidasextras">
<ion-checkbox ng-model="bebida.selected" >
<h2>{{bebida.ad_bebida_titulo}}</h2>
<p>R$ {{bebida.ad_bebida_valor}}</p>
</ion-checkbox>
</div>
</ion-list>
<button class="button button-block button-balanced">
<a ng-click="addToCart(bebida.ad_bebida_titulo,bebida.ad_bebida_valor)" class="button button-assertive button-clear icon ion-android-cart"> Continuar Comprando </a>
</button>
</ion-content>
My Controller:
$scope.bebidasextras = [];
var promise = $http.get('http://nhac.esy.es/api_carrinho/lista_bebida_extra.php?json=restaurantes')
.success(function(retorno) {
console.log(retorno);
$scope.bebidasextras = retorno; // não precisa fazer retorno.data
$scope.user = {
bebidasextras: [$scope.bebidasextras[1]]
};
$scope.checkAll = function() {
$scope.user.bebidasextras = angular.copy($scope.bebidasextras);
};
$scope.uncheckAll = function() {
$scope.user.bebidasextras = [];
};
$scope.checkFirst = function() {
$scope.user.bebidasextras = [];
$scope.user.bebidasextras.push($scope.bebidasextras[0]);
};
$scope.setToNull = function() {
$scope.user.bebidasextras = null;
};
$scope.getTotalSelected = function() {
var total = 0;
for(var i = 0; i < $scope.bebidasextras.length; i++){
var bebida = $scope.bebidasextras[i];
total += bebida.selected ? Number(bebida.ad_bebida_valor) : 0;
}
return total;
}
})
.error(function(erro) {
console.log(erro);
});
You can have an input box having a + and - button. Clicking upon which user can change the quantity of product selected.
If you can share some more details probably I would be able to answer in a better way.

Angular binding input value to list item to check if it is same

I have an array of 'word-pair' pairs which I am populating on my screen. Out of pairs, words will be populated in the left side list and on right side I am trying to have input field and when I enter corresponding pair value, checkmark should be shown.
My controller
.controller('DashCtrl', function($scope) {
$scope.message='Welcome to Ionic'
$scope.word_pair = [
{'word':'Nitish', 'pair':'Patkar'},
{'word':'Mihir', 'pair':'Janaj'},
{'word':'Jannes', 'pair':'Stubbi'},
{'word':'Martin', 'pair':'Wolle'}
]
})
My HTML:
<div class="row">
<!-- Left half of the screen to hold list of words -->
<div class="col col-50" align="center">
<ion-list>
<ion-item ng-repeat="item in word_pair">
{{item.word}}
</ion-item>
</ion-list>
</div>
<!-- Right half of the screen to hold list of pairs -->
<div class="col col-50"">
<ion-list>
<ion-item ng-repeat="item in word_pair">
{{item.pair}}
<input type="text">
<span><i class="ion-checkmark"></i></span>
</ion-item>
</ion-list>
</div>
</div>
How can I implement such an input field here? on I can perhaps use ng-if directive.
Try this-
$scope.word_pair = [
{'word':'Nitish', 'pair':'Patkar'},
{'word':'Mihir', 'pair':'Janaj'},
{'word':'Jannes', 'pair':'Stubbi'},
{'word':'Martin', 'pair':'Wolle'}
]
$scope.partnerCheckList = {};
for(var v in $scope.word_pair){
$scope.partnerCheckList[$scope.word_pair[v].word] = $scope.word_pair[v].pair;
}
$scope.showPartner = {};
$scope.partnerCheck = function(p,i_p){
if($scope.partnerCheckList[i_p] == p){
$scope.showPartner[p] = true;
}
}
<input ng-model="pair" type="text" ng-change="partnerCheck(pair,item.word)">
<span ng-show="showPartner[pair]"><i class="ion-checkmark"></i></span>
I think this should work.

Angular controller value seeming to revert to original value

After originally setting my controller weddingPrice value a change caused by a function does not seem to change the variable. Its probably a simple error- can anyone help?
When sendWeddingQuoteInfo() is called it seems to send the original weddingPrice, not the one which has been updated when the return journey toggle has been checked.
What should happen is that the wedding price should be set at the start through the local setup function. Then if the return journey toggle is switched to on, the returnJourneyChange() should be fired, changing the global weddingPrice. When the Submit Quote button is pressed this should take the updated weddingPrice and send it to the next page. Currently this does not happen- no idea why.
//wedding.html
<ion-view view-title="Wedding Pax Num" can-swipe-back="true">
<ion-content ng-controller="WeddingPaxCtrl">
<div class="card">
<div class="item centerText" style="background-color: brown;">
<h2>CALCULATE WEDDING</h2>
</div>
</div>
<div class="padding20Top padding20Bottom">
<h2 class="centerText">Select number of Passengers</h2>
<input ng-model="passengerNo" class="col col-50 col-offset-25 quoteTFieldWithListItems" type="textfield">
<h6 class="centerText">PASSENGERS</h6>
</div>
<ion-toggle ng-model="returnJourney.checked" ng-change="returnJourneyChange()">Return Journey
</ion-toggle>
<ion-toggle ng-show="returnJourney.checked" ng-model="midnightReturn.checked" ng-change="midnightReturn()">Return Journey After Midnight</ion-toggle>
<div>
<h6 class="logText centerText"> {{ getCostBreakDown() }}</h6>
</div>
</ion-content>
<div class="endOfPageButton">
<a href="#/app/home/tester">
<button class="button button-full button-clear" ng-click="sendWeddingQuoteInfo()">Submit Quote</button>
</a>
</div>
</ion-view>
//controller.js
app.controller('WeddingPaxCtrl', function($scope, $stateParams, PassData, WhichQuote, CostOfMarriage, StoreQuoteData, WeddingData, DataThrow) {
var item = WeddingData.getWeddingDataObject();
$scope.passengerNo = 49;
$scope.returnJourney = { checked: false };
$scope.midnightReturn = { checked: false };
var weddingPrice;
$scope.returnJourney;
$scope.midnightReturn;
setup();
var sendInfo;
function setup() {
console.log("setup called");
weddingPrice = CostOfMarriage.getPrice(item[0], $scope.passengerNo, $scope.returnJourney.checked, $scope.midnightReturn.checked);
}
$scope.returnJourneyChange = function() {
console.log("return j called");
weddingPrice = 1000;
console.log("wedding price is now" + weddingPrice);
}
$scope.midnightReturn = function() {
}
$scope.getCostBreakDown = function() {
}
$scope.sendWeddingQuoteInfo = function() {
// var weddingPrice = $scope.weddingPrice;
console.log("WeddingPrice is " + weddingPrice + weddingPrice);
var sendInfo = ["Wedding Hire", item[0], $scope.passengerNo, "Extra", weddingPrice];
StoreQuoteData.setQuoteData(sendInfo);
WhichQuote.setInfoLabel("Wedding");
}
})
I think your ng-controller attribute is not at the right place. So the scope of your submit button is different.
I've moved the controller to ion-view element then the click is working as expected.
Please have a look at the demo below or here at jsfiddle.
(I've commented a lot of your code just to make the demo work.)
var app = angular.module('demoApp', ['ionic']);
app.controller('WeddingPaxCtrl', function($scope, $stateParams) { //, WeddingData, DataThrow) {
//var item = WeddingData.getWeddingDataObject();
$scope.passengerNo = 49;
$scope.returnJourney = {
checked: false
};
$scope.midnightReturn = {
checked: false
};
var weddingPrice;
$scope.returnJourney;
$scope.midnightReturn;
setup();
var sendInfo;
function setup() {
console.log("setup called");
weddingPrice = 100; //CostOfMarriage.getPrice(item[0], $scope.passengerNo, $scope.returnJourney.checked, $scope.midnightReturn.checked);
}
$scope.returnJourneyChange = function() {
console.log("return j called");
weddingPrice = 1000;
console.log("wedding price is now" + weddingPrice);
}
$scope.midnightReturn = function() {
}
$scope.getCostBreakDown = function() {
}
$scope.sendWeddingQuoteInfo = function() {
// var weddingPrice = $scope.weddingPrice;
console.log("WeddingPrice is " + weddingPrice + weddingPrice);
//var sendInfo = ["Wedding Hire", item[0], $scope.passengerNo, "Extra", weddingPrice];
//StoreQuoteData.setQuoteData(sendInfo);
//WhichQuote.setInfoLabel("Wedding");
}
})
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<link href="http://code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet" />
<ion-view ng-app="demoApp" view-title="Wedding Pax Num" can-swipe-back="true" ng-controller="WeddingPaxCtrl">
<ion-content>
<div class="card">
<div class="item centerText" style="background-color: brown;">
<h2>CALCULATE WEDDING</h2>
</div>
</div>
<div class="padding20Top padding20Bottom">
<h2 class="centerText">Select number of Passengers</h2>
<input ng-model="passengerNo" class="col col-50 col-offset-25 quoteTFieldWithListItems" type="textfield">
<h6 class="centerText">PASSENGERS</h6>
</div>
<ion-toggle ng-model="returnJourney.checked" ng-change="returnJourneyChange()">Return Journey
</ion-toggle>
<ion-toggle ng-show="returnJourney.checked" ng-model="midnightReturn.checked" ng-change="midnightReturn()">Return Journey After Midnight</ion-toggle>
<div>
<h6 class="logText centerText"> {{ getCostBreakDown() }}</h6>
</div>
</ion-content>
<div class="endOfPageButton">
<!---<a href="#/app/home/tester">-->
<button class="button button-full button-clear" ng-click="sendWeddingQuoteInfo()">Submit Quote</button>
<!--</a>-->
</div>
</ion-view>

$scope.passengerNo returns undefined

I'm having problems with receiving the value from an angular expression.
What should happen is when the endOfPageButton is clicked it should pass through the passengerNo and the title. The title is being passed through fine however the passengerNo is always undefined.
Can you tell me how I can get this to update as the passengerNo should be controlled by a textfield and I though the updated value should be automatically injected?
Thanks!
//mainquote.html
<ion-view view-title="{{title}}" can-swipe-back="true">
<ion-content ng-controller="QuoteItemCtrl">
<div class="card">
<div class="item centerText" style="background-color: brown;">
<h6 class="headerTextPadding">REGION</h6>
<h2>{{title}}</h2>
</div>
</div>
<div class="padding40Top padding20Bottom">
<h2 class="centerText">Select number of Passengers</h2>
<input ng-model="passengerNo" class="col col-50 col-offset-25 quoteTField" type="textfield">
<h6 class="centerText">PASSENGERS</h6>
</div>
<div>
<h6 class="logText centerText">SCHOOLS > {{title}} > {{getCost()}} > # {{multiplier}}</h6>
</div>
</ion-content>
<div class="endOfPageButton">
<a href="#/app/home/finalquote">
<button class="button button-full button-clear" ng-click="sendQuoteInfo()">Submit Quote</button>
</a>
</div>
</ion-view>
//controller.js
app.controller('QuoteItemCtrl', function($scope, $rootScope, $stateParams, MakeSchoolQuote, DataThrow) {
var item = DataThrow.getDataObject();
$scope.passengerNo = 49;
$scope.title = item;
$scope.multiplier = MakeSchoolQuote.getMultipler(item);
$scope.getCost = function() {
$scope.pax = $scope.passengerNo;
var cost = $scope.multiplier * $scope.passengerNo
console.log("passenger numbers are" + $scope.pax);
return cost;
}
$scope.sendQuoteInfo = function() {
var data = [$scope.title, $scope.passengerNo, "N/A"];
var sendData = DataThrow.storeDataObject(data);
}
})

Why does my function in my custom directive trigger twice upon re-entering a screen?

I have a custom directive that returns various template files to build survey questions based on their type (select, checkbox etc) but the behaviour of my directive changes based on whether I have already accessed it despite having completely left the url and hopefully destroyed any remnant of it.
Basically changeDate is supposed to run once upon entering the directive (triggered by the setting of tempdate) which should update a label on the template. This actual input element is being hidden. The problem is that if I leave the page that uses this template completely and then go back into it the changeDate function runs twice regardless of what is inside it or what it does.
datepicker.html
<div class="question-title q-element"><div>{{question.question[language]}}</div></div>
<div class="question-response">
<ng-form name="innerForm">
<span>
<span ng-show="question.response" class="select-label-pos">{{formattedDate}}</span>
<span ng-show="!question.response" class="select-label-pos">Pick a Date</span>
</span>
<input ng-change="changeDate()" ng-required="{{question.mandatory}}" ng-model="tempdate" type="date">
</ng-form>
</div>
inputDirective.js
(function(){
"use strict";
angular.module('gather.directives.inputDirective',
[
]).directive('inputDirective',
[
function(){
return {
link: function(scope, element, attrs){
scope.language = attrs.language;
if(attrs.inputDirective==="datepicker"){
var first = true;
if(attrs.draft==='false') {
//console.log('not a draft, setting default date');
scope.tempdate = new Date(1999, 3, 3);
}else{
scope.tempdate = new Date(scope.question.response);
//console.log('got a draft, getting response date');
}
console.log('Running Datepicker, the response is ', scope.question.response);
scope.logOut = function(){
console.log('BUILDING TEMPLATE');
console.log(scope.question.qid);
};
scope.changeDate = function(){
// console.log('first: ',first);
//console.log('attrs.draft: ', attrs.draft);
if(first===true&&attrs.draft==='false'){
//if its the first time and not a draft just flip the switch
first = false;
//console.log('Not a draft, first load/change: Just flip the switch');
//console.log(scope.question);
}else if(attrs.draft==='true'){
//if draft is true we will already have a value, set the tempdate abd update the label
attrs.draft = 'false';
first = false;
var d = new Date(scope.question.response);
scope.day = d.getDate();
scope.month = d.getMonth()+1;
scope.year = d.getFullYear();
scope.formattedDate = scope.month + '-'+scope.day+'-'+scope.year;
//console.log('Survey is a draft: Update the datepicker label with the response');
} else{
//if its not the first time and draft is false we start normal updates of the values
var d = new Date(scope.tempdate);
scope.day = d.getDate();
scope.month = d.getMonth()+1;
scope.year = d.getFullYear();
scope.formattedDate = scope.month + '-'+scope.day+'-'+scope.year;
scope.question.response = scope.tempdate;
//console.log('Not a draft, not first change/load: Update the datepicker label with the response');
}
};
}
},
templateUrl: function(elem, attrs, scope){
console.log();
return "views/question-types/"+attrs.inputDirective+"-question.html";
},
};
}]
);
survey.html
<a id="top"></a>
<div id="survey" class="snap-container">
<div id="header">
<h1>Capture Data </h1>
<a href="#/home">
<div class="home-button">
</div>
</a>
<div class="menu-button" snap-toggle="right">
</div>
</div>
<div class="surveys-container">
<div id="template" ng-repeat="asset in template | filter:{type:'html'}">
<ng-include src="addAssetPath(asset.path)"></ng-include>
</div>
<div ng-show="currentGroup == false" class="groupMenu overlay-view">
<h2 class="group-title">Lead Capture</h2>
<div ng-repeat="group in survey.groups|orderBy:'group_order'" >
<div ng-click="changeGroup(group.group_name.en)" class=" menu-group-title">
<span>{{group.group_name.en}}</span>
<span ng-if="group.group_name.en != 'Barcode'" class="arrow-icon ui-icon"></span>
<span ng-if="group.group_name.en == 'Barcode'" class="scan-icon ui-icon"></span>
</div>
</div>
<button class="action-button client-gradient-submit" ng-click="submitForm()">Submit</button>
<button class="action-button client-gradient-draft" ng-click="saveDraft()">Save</button>
</div>
<div ng-show="currentGroup == group.group_name.en" class="group group-container overlay-view" ng-repeat="group in survey.groups|orderBy:'group_order'">
{{logTest(group.group_name.en, $index)}}
<h2 class="group-title">{{group.group_name.en}}</h2>
<div class=" question-container {{question.css_class.en}}" ng-repeat="question in group.questions|orderBy:'question_order'">
<div class="" ng-switch="question.type">
<div input-directive="text" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="S">
</div>
<div input-directive="select" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="!">
</div>
<div input-directive="radio" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="L">
</div>
<div input-directive="textarea" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="T">
</div>
<div input-directive="checkbox" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="M">
</div>
<div input-directive="datepicker" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-when="D">
</div>
<div input-directive="other" question="question" language="{{surveyLang}}" draft="{{draft}}" ng-switch-default>
</div>
</div>
</div>
<button class="done-button" ng-click="changeGroup(false)" ng-show="currentGroup != false">Done</button>
</div>
</div>
</div>

Resources