how to get json data in suggestion using type-ahead in angularjs - 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!

Related

angular typahead fetch results with starting letter only

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.

how do I take value from this $scope

so I have this code in my chatting application, its for send message to the partner.
$scope.messages = {
from : $scope.datauser['data']['_id'],
fromname : $scope.datauser['data']['nama'],
to : $scope.tmpuserid,
message : $scope.tmp['sendmessage'],
time : moment()
};
I want to add text-to-speech features in my application, the question is how I take the value from $scope.messages but just the message because if I just write $scope.messages, TTS will read all data from from until time
Not sure exactly what you want, but it would be something like:
<div ng-repeat="message in messages">
<p>{{message.message}}</p>
</div>
EDIT: This answer is for iterating through an array of messages.
If it were just one messages object it would be:
<p>{{messages.message}}</p>
Maybe I'm missing something in your question, but if all you want to extract just the message from the messages $scope object you would use JS object dot notation e.g.
var justMessage = $scope.messages.message;
// justMessage = $scope.tmp['send message'];
// OR parse an array
var myPartnerMessages = [];
angular.forEach($scope.messages, function(msg, key) {
this.push(msg.message);
}, myPartnerMessages);
You can get the value from $scope as follows:
View.html
<div ng repeat="item in messages">
<div>{{item.message}}</div>
</div>
You just call the property as $scope.messages.message. Or since you already had it on another scope variable, you can call it as $scope.tmp['sendmessage'].
If you are trying to access from the HTML side, you would use it as this:
<p>{{messages.message}}</p>
Not exactly sure if this is what you need from reading your question, though.
if it is a single object not an array if is an array you should use ng-repeat
On js end you can get it by
$scope.messages.message
On html end you can get it by
{{messages.message}}

How to update view in angular, when database has changed?

Ive got a SPA using angular and 2 databases in firebase.
So theres a control (with 2 options) where i'd like choose database to get data. For example first option means 1st database, second option means 2nd one.
The question is: "how to update view in angular, when database has changed".
<select class="form-control" ng-model="level" ng-options="lvl in lvls"></select>
<div>{{data}}</div>
in controller
var levelString = "https://amber-inferno-9289.firebaseio.com/" + $scope.level + "/";
$scope.dictionary = new Firebase(levelString);
$scope.dictionary.on('value', function(snapshot){
$scope.data = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
I think what you're looking to do is use the ng-change directive on your select and refactor your dictionary set up logic into a function that is called on select change.
<select class="form-control" ng-model="level" ng-options="lvl for lvl in lvls" ng-change="setUpDictionary(level)"></select>
Then in your controller, create the setUpDictionary function to set $scope.dictionary to a new Firebase pointing at a different url etc.
I think this is what you're looking for based on what I could make from your question.
Hope it helps you out!

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.

Setting default <select> value with asynchronous data

I have a drop-down list
<select ng-model="referral.organization"
ng-options="key as value for (key, value) in organizations">
</select>
where organizations is filled using a $http request. I also have a resource referral which includes several properties, including an integer organization that corresponds to the value saved in the drop-down. Currently, the drop-down works fine and selecting a new value will update my referral resource without issue.
However, when the page loads the drop-down is blank rather than displaying the value of referral.organization that was retrieved from the server (that is, when opening a previously saved referral form). I understand that this is likely due to my resource being empty when the page first loads, but how do I update the drop-down when the information has been successfully retrieved?
Edit:
{{ organizations[referral.organization] }} successfully lists the selected value if placed somewhere else on the page, but I do not know how to give the tag this expression to display.
Second Edit:
The problem was apparently a mismatch between the key used in ngOptions and the variable used in ngModel. The <select> option's were being returned as strings from WebAPI (despite beginning as Dictionary) while the referral model was returning integers. When referral.organization was placed in ngModel, Angular was not matching 2723 to "2723" and so forth.
I tried several different things, but the following works well and is the "cleanest" to me. In the callback for the $resource GET, I simply change the necessary variables to strings like so:
$scope.referral = $resource("some/resource").get(function (data) {
data.organization = String(data.organization);
...
});
Not sure if this would be considered a problem with Angular (not matching 1000 to "1000") or WebAPI (serializing Dictionary<int,String> to { "key":"value" }) but this is functional and the <select> tag is still bound to the referral resource.
For simple types you can just set $scope.referral.organization and it'll magically work:
http://jsfiddle.net/qBJK9/
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations">
</select>
</div>
-
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: 'c'
};
}
If you're using objects, it gets trickier since Angular doesn't seem smart enough to know the new object is virtually the same. Unless there's some Angular hack, the only way I see forward is to update $scope.referral.organization after it gets loaded from the server and assign it to a value from $scope.organizations like:
http://jsfiddle.net/qBJK9/2/
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c.name for c in organizations"></select>
{{referral}}
<button ng-click="loadReferral()">load referral</button>
</div>
-
function MyCtrl($scope) {
$scope.organizations = [{name:'a'}, {name:'b'}, {name:'c'}, {name:'d'}, {name:'e'}];
$scope.referral = {
organization: $scope.organizations[2]
};
$scope.loadReferral = function () {
$scope.referral = {
other: 'parts',
of: 'referral',
organization: {name:'b'}
};
// look up the correct value
angular.forEach($scope.organizations, function(value, key) {
if ($scope.organizations[key].name === value.name) {
$scope.referral.organization = $scope.organizations[key];
return false;
}
});
};
}
You can assign referral.organization to one of objects obtained from ajax:
$scope.referral.organization = $scope.organizations[0]
I created simple demo in plunker. Button click handler changes list of objects and selects default one.
$scope.changeModel = function() {
$scope.listOfObjects = [{id: 4, name: "miss1"},
{id: 5, name: "miss2"},
{id: 6, name: "miss3"}];
$scope.selectedItem = $scope.listOfObjects[1];
};
The other answers were correct in that it usually "just works." The issue was ultimately a mismatch between the organization key (an integer) stored inside $scope.organizations and the key as stored in the $http response, which is stored in JSON and therefore as a string. Angular was not matching the string to the integer. As I mentioned in my edit to the original question, the solution at the time was to cast the $http response data to a string. I am not sure if current versions of Angular.js still behave this way.

Resources