angular typahead fetch results with starting letter only - angular-ui-typeahead

JS Code below :
$scope.startsWith = function(state, viewValue) {
return state.substr(0, viewValue.length).toLowerCase() == viewValue.toLowerCase();
}
html< start tag< input name="states" id="states" type="text" placeholder="Search Countries..." ng-model="selected" typeahead="state.COUNTRY_CODE as state.COUNTRY_DESC for state in states | filter:$viewValue:statestartsWith | limitTo:8">
This is still not searching for first letter, it is giving results matching in middle of the string also. Please help

The order of filters are incorrect.
typeahead="state.COUNTRY_CODE as state.COUNTRY_DESC for state in states | startsWith:$viewValue | limitTo:8"
In order to make it work, you have to define the function startsWith as a filter in your angular app.
See this angular documentation
Also your parameter name is state but the typeahead will return the country code of the state so be careful with your variable names.

Related

how to get json data in suggestion using type-ahead in angularjs

I am new in angular.js, I am creating a suggestion box for my form using typeahead directive referring this example, but my data is coming from json file (webservice call).
I am getting an error on this line
<input ng-model="selected" ng-change="getdata()" typeahead="dataAddress for dataAddress addressData" | filter:$viewValue | limitTo:2/>
Angular code:
$scope.getdata =function(){
$http.get("address.json&id=2&q="+$scope.selected).then(function (res) {
$scope.addressData = res.data.response.topSuggestions;
console.log($scope.addressData)
});
};
json content:
{"response":{"sequenceNumber":2,"topSuggestions":[{"address":{"detectedLanguage":"en","isComplete":true,"searchBarString":"aaaaaasdasdd","string":"aaaaaasdasdd","municipalityName":"aaa","postalCode":"1007"}}]}}
I want to select address and string.
I called the service for each single character the user hit by adding that, search.
Please help.
Thanks in advance!

Angular : Getting values of check box when it is checked

This is my view I want to get the values such as diabetes , or htn etc cause I want to store them in a string format. But the way I am dooing it right now I get it in an object format
font(color ='green', size ='3')
strong Past History
.checkbox
label
input(type='checkbox', value='',name = 'diabetes', ng-model = 'formData.history.diabetes')
| DIABETES
.checkbox
label
input(type='checkbox', value='',name = 'htn', ng-model = 'formData.history.htn')
| HTN
.checkbox
label
input(type='checkbox', value='',name = 'asthma', ng-model = 'formData.history.asthma')
| ASTHMA/COPD
Now in my controllers when I
console.log($scope.formData.history)
I get an output like:
`{diabetes : true}`
But I want to send this data to my backend in a String form. Any idea how to get only "diabetes" or "htn" . thank you
The type of the value binded to the checkbox model is by default a boolean. That's why you get true or false as values.
Use the directives ng-true-value and/or ng-false-value if you want to change that. Here is an example, in html:
<input type="checkbox" name="htn" ng-model="formData.history.htn" ng-true-value="'htn'">
By your scenario you should declare data-ng-model as Array.
Your answer is here
<input type="checkbox" ng-model='formData.history[1]' ng-true-value="'htn'">
font(color ='green', size ='3')
strong Past History
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='diabetes', name = 'diabetes', ng-model = 'formData.history.diabetes')
| DIABETES
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='htn', name = 'htn', ng-model = 'formData.history.htn')
| HTN
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='asthma', name = 'asthma', ng-model = 'formData.history.asthma')
| ASTHMA/COPD
Check how I used data-ng-true-value attribute if checked that will contain the value. Similarly you can have data-ng-false-value when it is unchecked. That should give you {diabetes : diabetes}, {htn: htn} But the way you have written your ng-model it will act like radio button if you need multiple selection your ng-model need to be modified to fit the scenario. Hope that helps
JSON.stringify($scope.formData.history)
This should solve your problem if you want your data in a JSON format.

Angular JS Filter On date

I was wondering if anyone could help me with filter on dates within ng-repeat
I have a text field that I enter the search text into for filter the results in my table
take this cut down example`
<tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText">
<td>{{credential.createdDate | date:'medium'}}</td>
</tr>`
credential.createdDate comes back in the rest call in the format 2015-03-24T21:19:49Z
When I attach the medium date filter - it displays as Mar 24, 2015 9:19:49 PM
However when i search on the String Mar or 9:, I get no results. Angularjs searches on the base object and ignores the filter.
I have read other options online where the person recommends adding different date formats into the json object but unfortunately that is not an option for me
Any help on this would be appreciated
Cheers
Damien
You can use a custom function for the filter.
https://docs.angularjs.org/api/ng/filter/filter
<tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText:compareCredentialDate">
<td>{{credential.createdDate | date:'medium'}}</td>
</tr>
In your controller, put a
$scope.compareCredentialDate = function(credential, expected) {
// you have to inject '$filter' to use this:
var dateFilter = $filter('date');
// this is the value that "credential.createdDate | date:'medium'"
// evaluates to:
var formattedDateString = dateFilter(credential.createdDate, 'medium');
// hypothetical matching method - you can implement whatever you
// want here:
var isMatch = formattedDateString.indexOf(expected) >= 0;
return isMatch;
}

Variable substitution while using messageformat with angular-translate

I'm using angular-translate with messageformat interpolation to pluralize some strings.
(for those who don't know what I'm talking about: http://angular-translate.github.io/docs/#/guide/14_pluralization).
It's going pretty well, but I can't figure out how to use variables instead of constants.
$translateProvider.translations('it', {
SELECTED_CATEGORIES: "{NUM, plural, =0{Nessuna categoria selezionata} one{1 categoria selezionata} other{# categorie selezionate}}"
}).translations('en', {
SELECTED_CATEGORIES: "{NUM, plural, =0{No category selected} one{1 selected category} other{# selected categories}}"
});
and this is the HTML code:
<span>{{ 'SELECTED_CATEGORIES' | translate:"{'NUM': 2 }" }}</span>
This works but if I use
<span>{{ 'SELECTED_CATEGORIES' | translate:"{'NUM': my_variable_in_the_scope }" }}</span>
I get an error. I tried to use quotes, double quotes and similar, but nothing seems to work.
I know that messageformat doesn't support expression evaluation, but I hoped that a variable substitution would have worked.
Any Idea?
Well, the correct solution should be passing the scope and accessing the value within the messageFormat code.
You can do this easily like this:
$translateProvider.translations('it', {
SELECTED_CATEGORIES: "{my_variable_in_the_scope , plural, =0{Nessuna categoria selezionata} one{1 categoria selezionata} other{# categorie selezionate}}"
}).translations('en', {
SELECTED_CATEGORIES: "{my_variable_in_the_scope , plural, =0{No category selected} one{1 selected category} other{# selected categories}}"
});
And your HTML:
<span>{{ 'SELECTED_CATEGORIES' | translate:your_scope }}</span>
Please note: I passed "your_scope" within the translate-filter and accessed "my_variable_in_the_scope" within the messageFormat code.
This should be the best solution.
To use variables in angular filters, you have to use
filter:{key: value} without quotes
E.g. my filter replaceVariable is used to enable rails yml placeholders being replaced with a js variable
usage:
{{ sometranslation | replaceVariable:{count:results} }}
filter:
// replaces {%count} in yml translations to work with angular
filters.filter('replaceVariable', function () {
"use strict";
return function (string, variable) {
var replace = string.replace(/%\{[\w\s]*\}/, variable.count);
return replace;
};
});
so i guess with translate you have to use it the same way. I remember i couldnt get this to work either which is why i chain my custom filter after
somevalue | translate | myCustomFilter

Inject $scope into filter (AngularJS)

What I'm trying to do:
Im using a ng-repeat directive on an associative array, which I want to filter. The build in angular filter isn't working on associative arrays/hashes. Because of that, I'm trying to write my own filter (inspired by http://angularjs.de/artikel/angularjs-ng-repeat; it's in german, but the important code is below the headline "Beispiel 2: Filtern von Hashes mittels eigenem Filter" which means "Example 2: Filter Hashes with your own filter").
The ng-repeat:
tr ng-repeat="(key, machine) in machines | customFilter | orderObjectBy:'name':false"
note: orderObjectBy is also a customFilter.
The filter:
toolApp.filter('customFilter', [function(){
return function(machines){
var result = {};
angular.forEach(machines, function(machine, key){
/*if(machine.name.contains(filter)){
result[key] = machine;
}*/
//if(machine.name.contains("a")){
result[key] = machine;
//}
});
return result;
};
}]);
The filter works with a hardcoded "filter-criterium". But I want to have a textbox above the list, in which the user can enter the "filter-criterium". My Problem is, that i don't know how to insert this value into the filter. I don't find much on the Internet and what i found, didn't work for me.
Has anyone an idea how to insert the value oder maybe a different approach.
Huge thanks in advance for every answer! If you need more information, let me know! I tried to keep it short :>.
Greetings from Germany
you may have parameters to your custom filter.
suppose you have an input field:
<input ng-model="myParam">
and an ng-repeat like yours:
<tr ng-repeat="(key, machine) in machines | customFilter:myParam | orderObjectBy:'name':false" >
then you may access this parameter in your custom filter:
toolApp.filter('customFilter', [function(){
return function(machines, myParam){
var result = {};
angular.forEach(machines, function(machine, key){
if(machine.name.contains(myParam)){
result[key] = machine;
}
});
return result;
};
}]);
note:
Pay attention that the myParam value is initialized with an "undefined" value. You have to set a default value in the controller or handle it in the customFilter. Otherwise you will only see your list, after you started typing.

Resources