How to do ajax postback with typeahead directive of Angular-ui-bootstrap

444 views Asked by At

I am using Angular-UI TypeAhead in my mvc application.

Here is my HTML source:

<div data-ng-app="v">
    <div ng-controller="TypeAheadController">
        <input type="text" id="txtType" ng-model="selected" typeahead-on-select="callBack($item,$model,$label)" typeahead="state as state.Name for state in states | filter:$viewValue | limitTo:8" class="form-control">
    </div>
</div>

Here is my js file:

    var v = angular.module('v', ['ui.bootstrap']);

v.factory('serverCallMakerFactory', ['$http', serverCallMakerFactory]); 

function serverCallMakerFactory($http) {
    var serverCallMakerFactory = {};
    serverCallMakerFactory.callServer = function (url) {
        return $http.get(url);
    };
    return serverCallMakerFactory;
}

v.controller('TypeAheadController', ['$scope', 'serverCallMakerFactory', $scope,TypeAheadController]);


function TypeAheadController($scope, serverCallMakerFactory) {

    $scope.selected = undefined;
    $scope.states = [{ 'ID': 1, 'Name': 'Alabama' }, { 'ID': 1, 'Name': 'Alaska' }, { 'ID': 1, 'Name': 'Arizona' }, { 'ID': 1, 'Name': 'Arkansas' }];
    $scope.callBack = function ($item, $model, $label) {
        serverCallMakerFactory.callServer("/Customer/DisplayJsonCustomer")
        .success(function (data) {
            debugger;
        });
    };
}

what I want to do is make a json call with the id of the country selected by user.

I tried using typeahead-on-select attribute. but in callBack function I am not able to get $http service. Can anybody please help me?

Basically in this post back I am going to pull out the data as a source for another typeahead I am going to use. If anyone has better solution to this requirement please suggest.

1

There are 1 answers

0
dbugger On BEST ANSWER

Just call an angular service from your controller that returns the data. It can use $http or any other method. In this example it's calling a service that returns a promise. When it completes it will call the then() bit of code and you can do what you want.

$scope.callBack = function ($item, $model) {
        var aPromise = someService.getMoreData($item.ID);
        aPromise.then(function (data) {

            //use the data or do something else with it
            $scope.yourProperty = data;

        });

    };