md-select default value with condition - angularjs

i'm using md-select to pick a year there is a scenario that when you fill up the form in the first time you will get a default value of latest year else you will get the previous value.
here's my view(slim format)
md-input-container flex=""
label Year
md-select name="type" ng-model="detail.year" ng-change="addYear(detail.product_id)"
md-option ng-repeat="year in years" value="{{year.year}}" ng-selected="detail.year? == null ? year.year : $first"
| {{year.year}}
and here's my controller for iterate the year (coffee format)
$scope.years = []
start_year = (new Date).getFullYear()
i = start_year
while i >= 2005
$scope.years.push(year: i)
i--
my error

putting comment as answer...
ng-selected="detail.year? == null ? year.year : $first" | {{year.year}}
don't add logic in html, keep it in JS files, it will be more easily testable + you dont have to fight with angular syntax support

Related

Ionic/Angular ion-datetime with condition

I have the following in Ionic and I'd like to let the user choose a datetime value but with one condition: If hour is equal to '21' then minutes must be '00' (not '30'), otherwise minutes value can be equal to '00' or '30'. Ideas?
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
[minuteValues]="hour != 21 ? '00,30' : '00'"
[(ngModel)]="time"
name="time"
required>
</ion-datetime>
It was not possible because the "minuteValue" is set first when u click on ion-datepicker to select date & time.
one way to achieve this is to compare your selected hour in .ts file and assign particular value based on hour to the minute like below.
In .html file.
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
minuteValues="0,30"
[(ngModel)]="time"
name="time"
displayFormat="MM DD,YYYY HH:mm"
(ionChange)="timeValue()"
required>
</ion-datetime>
In .ts file:
timeValue()
{
let hour = this.time.split('T')[1].split(':')[0];
let minute = this.time.split('T')[1].split(':')[1];
if(Number(hour) === 21)
{
minute = '00';
}
let date = new Date(this.timey);
date.setHours(Number(hour));
date.setMinutes(Number(minute));
console.log("------------"+date);
}

Automation of selecting future and past date from datepicker

I am working on e2e using protractor. There is a scenario where I need to select one future date(10 days ahead from today), one past date(5days previous from today). If today's date is 12/20/2017 I need to select 12/30/2017 (future date) and 12/15/2017(past date) from two separate datepickers. I tried the below code, but everytime today's date is getting selected even though future date is specified by adding the number of days(10). Future date is correctly printed on console, but it is selecting today's date from the datepicker. Please let me how to do this.
function consentEffectiveDate(){
var picker = element(by.model('case.consentEffectiveDate'));
// get today's date
var today = new Date();
var dd = today.getDate()+10;
console.log("date: "+dd);
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
picker.sendKeys(today);
console.log("date:"+today);
Thanks in advance for any help.
html code
<input type="text" readonly="readonly"
class="form-control effectiveDate ng-pristine ng-valid ng-valid-pattern ng-touched"
name="effectiveDate" id="effectiveDate"
ng-model="case.consentEffectiveDate" placeholder="MM/DD/YYYY"
ng-pattern="/^([0]?\d{1}|[1][0-2])\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([1-9]{1}\d{3}))$/"
data-ng-change="model.compareDates(case.consentEffectiveDate, case.consentExpiresDate, new_consent);"
ng-class="{ 'has-error' : new_consent.effectiveDate.$invalid && (new_consent.effectiveDate.$dirty || submitted)}"
style="">
I experienced the same issue before. For me it was that the date-picker wasn't focused by protractor and therefore the date wasn't sent to the input field.
Try focusing the element by clicking it first and then pass the keys.
var picker = element(by.model('case.consentEffectiveDate'));
picker.click().sendKeys(today);
If there is a possibility that the date is pre-filled, you could write it like this to remove the previous date from the picker before entering the new date.
picker.click().sendKeys(protractor.Key.CONTROL, "a", protractor.Key.NULL, today);
Hope this helps

Edit the selected option text in "ng-options" select-list

I need to add the text "(Default)" to the selected-option text. please help me...
The text should be "Visa 1881 (Default)".
But its only showing "Visa 1881". Here is my code:
<select ng-options="item.brand + ' ' + item.last_digits for item in approvedinvoicesCtrl.current_job.cards" ng-model="approvedinvoicesCtrl.GetCard"></select>
var vmc = this;
vms.current_job = response.data.payment_info;
for (var i = 0; i < vmc.current_job.cards.length; i++){
if (vmc.current_job.cards[i].is_default){
vmc.GetCard = vmc.current_job.cards[i] + ' (Default)';
}
}
What I get is this,
And what I need is this.
Thanks.
Try to initialize using ng-init default value:
<select ng-init=" approvedinvoicesCtrl.GetCard = initialValue"
ng-model="approvedinvoicesCtrl.GetCard"
ng-options="item.brand + ' ' + item.last_digits for item in approvedinvoicesCtrl.current_job.cards">
</select>
Updated:
jsfiddle link:
https://jsfiddle.net/avnesh2/g2j6863a/6/
working as you want.
Hope this will work.
In your if() statement, you're assigning a value to cards[i].is_default instead of evaluating it. So not only your condition will always be true , cards[i].is_default value will also be (String) "true".
if (this.current_job.cards[i].is_default = 'true')
// Should be
if (this.current_job.cards[i].is_default == 'true')
You should use == instead of =.
Do you want the option text to be Visa 1881 (Default) instead of Visa 1881?
In this case you can just add a string to the value:
this.GetCard = this.current_job.cards[i] + ' (Default)';

angular filter on click by 'last week' data

Hi I am new in angular and making my first module. This article is very helpfull. I want to filter my data by lastweek records. I have already found days by current date and given date in mysql query, On button click I am just setting value like DisTopic=1 and this works fine.
May you please tell me how can I apply filter for a range like day>=1 && day<=7
I am using below:-
filter:{'topic': DisTopic,'attachment':attch, 'days':day}
Please help me.
Solution 1: with angular-filter module
As stated by other users, you could indeed do that with a custom filter. However, if you find yourself writing a lot of custom filters, I'll advise you have a look at angular-filter module. With this module you can do what you need with the pick filter :
<div ng-repeat="task in tasks | pick: 'days >= 1 && days <= 7'">{{task.name}}</div>
See demo fiddle
Solution 2: Custom filter with parameters
Template:
<div ng-repeat="task in tasks | dayFilter: 1 : 7">{{task.name}}</div>
Javascript:
app.filter('dayFilter', function() {
return function(input, startDay, endDay) {
var filterFunction = function (item) {
return item.days >= startDay && item.days <= endDay;
};
return input.filter(filterFunction);
};
});
See updated demo fiddle
Custom filter example, you can modify as per your need.
Controller
$scope.search = function (item) {
if ($scope.searchUser == null || $scope.searchUser.trim() == "")
return true;
if (item.FirstName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.LastName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.Role.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1) {
return true;
}
return false;
};
and than call it in your view
| filter:search
So, depending on your requirement, you can pass as many parameters and modify method in controller.
//Below code solve my problem.
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return Math.ceil((firstThursday - target) / 604800000) - 1; // 604800000 = 7 * 24 * 3600 * 1000
};

element(by.binding('...'),getText() gets a whole block of text instead of only the element

I am testing the result of {{price}}and {{getAdditionalKm}} of my AngularJS Application with Protractor. Here is part of the html I want to test:
<h1>{{ price(distance, time, time_standing, airport) | currency }}</h1>
<p>Preis im Detail:<p>
...
<b>Distanz</b><br>
{{ getFreeKm( time) }} Freikilometer<br>
{{ getAdditionalKm(distance, time) }} km a {{ fee_additionalkm | currency }} Zusätzlicher Kilometer Preis = {{ getFee_additionalKm(distance, time) | currency }} Kilometer Preis<br>
...
In my protractor Scenario I run expect(element(by.binding('price')).getText()).toEqual('20,30 €'); which works as expected and only gets the price ('20.30 €').
However running expect(element(by.binding('getAdditionalKm')).getText()).toEqual('50');gets me everything after the {{ price }} element. This is the output if I run the Protractor Test:
...
Failures:
1) c2g test get price with 50 additional kms
Message:
Expected 'Zeit
0 Tage a 59,00 ? = 0,00 ?
0 Stunden a 14,90 ? = 0,00 ?
20 Minuten a 0,29 ? = 5,80 ?
Distanz
50 Freikilometer
50 km a 0,29 ? Zusätzlicher Kilometer Preis = 14,50 ? Kilometer Preis
Sonstiges
0,00 ? Zeit stehend
0,00 ? Flughafenpauschale' to equal '50'.
...
Why is protractor not selecting only the {{getAdditionalKm}} element? Do I need to change the html?
getAdditionalKm is not within its own element, so the entire element that contains it gets selected. Instead of using the .toEqual comparison to .toContain. If possible you could also put the getAdditionalKm binding in its own element.

Resources