1

Using AngularJS with C# webapi here.

I am creating an input control, when the user starts typing in it I want to use typeahead and show the returned data.

I have setup the typeahead as below:

HTML:

  <input type="text" name="uName" ng-model="uName" autocomplete="off" required class="form-control input-medium" placeholder="Enter user name..."
   typeahead="uName for uName in getUserNames($viewValue)" />

Controller:

    $scope.getUserNames = function (search) {
        myService.getUserNamesFromApi(search).then(function (response) {
            $scope.foundNames = [];
            if (response.length > 0) {
                for (var i = 0; i < response.length; i++) {
                    $scope.foundNames.push({ 'uName': response[i].uName });
                }
                return $scope.foundNames;
            }
        });
    };

The Data returned from my API is an array for example as:

0: {fName: "Adam", lName: "Smith", uName: "asmith123"},
1: {fName: "John", lName: "Bambi", uName: "jbambi456"}

And so on...

I am trying to get the uName part and push that to my array and then I return that array. But with this code currently it shows nothing, no error.

What am I missing here?

0

2 Answers 2

2

It should be as,

 typeahead="uName as uName.uName for uName in getUserNames($viewValue)" />
Sign up to request clarification or add additional context in comments.

Comments

1

You missed to return a promise from your getUserNames function. That's how typeahead loads asynchronous collection, as soon as you type in something. And also return $scope.foundNames; from outside if condition.

$scope.getUserNames = function (search) {
    // return promise here.
    return myService.getUserNamesFromApi(search).then(function (response) {
        $scope.foundNames = [];
        if (response.length > 0) {
            for (var i = 0; i < response.length; i++) {
                $scope.foundNames.push({ 'uName': response[i].uName });
            }
        }
        // return result from here.
        return $scope.foundNames;
    });
};

2 Comments

Thanks that was missing.
@user1563677 Glad it know it helped, Thanks :)

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.