1

I am trying to obtain data from a local server using JSON (not JSONP) and display it in a typeahead using Angular UI bootstrap and Angular. I was able to get timeout() and jsonp to work from other examples I found on this site, so I know promises works.

function DepedencyCtrl($scope, $http, $timeout, filterFilter) {
...
$scope.typeahead = function(type, name) {
  return $http.get('pulldata', {params: {type: type, name: name}}).success(function(data){
    return filterFilter(data, name);
  }, 1000);
};  

When I run this code in a debugger, the return filterFilter line runs. I can see my data in JSON form, but I get lost stepping through the Angular code. Is there something I'm missing?

1 Answer 1

1

You're providing angular with a callback function to call on http success. The http call is succesful long after your typeahead function returns. A big thing in javascript you have to wrap your head around is there's a ton of asynchcrony going on. You kick off an http request, give it a callback, and go away. Something in angular eventually calls your success function, and when your success function returns you end up back in angular land.

Angular is nice in that on most events, it will check for changes for any values/expressions it knows it needs to watch for changes. It will then apply whatever behavior needs to occur on those changes. So Angular has a special process called $digest that does this. This behavior is often billed as angular's "2 way binding" feature.

You want to take advantage of angular's 2-way bindings, something like:

$scope.typeaheadText = "";
$scope.typeahead = function(type, name) {
  return $http.get('pulldata', {params: {type: type, name: name}}).success(function(data){
    $scope.typeaheadText = data.typeaheadText;
  }, 1000);
};  

Corresponding HTML:

<span ng-controller="YourTypeaheadCtrl">
{{typeaheadText}}
</span>
Sign up to request clarification or add additional context in comments.

1 Comment

Also, the reason why $timeout and $http might had worked for the OP, is because AngularJS views resolve promises. It's better if you resolve them like this in your controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.