using $http in angular.js factory

前端 未结 2 1817
长情又很酷
长情又很酷 2021-02-10 03:08

In my app I am using angular.js and jquery ui autocomplete. I had the same problem that is discussed HERE The accepted answer there works great for me and is exactly what I nee

2条回答
  •  星月不相逢
    2021-02-10 03:21

    This is how you can do it:

    app.factory('autoCompleteDataService', ['$http', function($http) {
        return {
            getSource: function() {
                return function(request, response) {
                    $http.get(url).success(function(data) {
                        response(data);
                    });
                }
            }
        }
    

    }]);

    However, if you want to download the entire data first and allow the autocomplete widget to search the data on the client side, this is an example how you can do it:

    app.directive('autoComplete', function(autoCompleteDataService, $http) {
    return {
        restrict : 'A',
        link : function(scope, elem, attr, ctrl) {
            autoCompleteDataService.getData(function(err, data) {
                if (err) {
                    console.log("Could not retrieve data.");
                    return;
                }
    
                elem.autocomplete({
                    minLength: 0,
                    source: data,
                    focus: function( event, ui ) {
                        elem.val( ui.item.label );
                        return false;
                    },
                    select: function( event, ui ) {
                        elem.val( ui.item.label );
                        return false;
                    }
                })
                .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
                    return $( "
  • " ) .append( "" + item.label + "" ) .appendTo( ul ); }; }); } };
  • });

    app.factory('autoCompleteDataService', ['$http', '$rootScope', function($http, $scope) {
    return {
        getData: function(callback) {
            if ($scope.data) {
                return callback(null, $scope.data);
            }
    
            $http.get('URL')
            .success(function(data) {
                $scope.data = data;
                return callback(null, data);
            })
            .error(function(data) {
                return callback(true, null);
            });
        }
    }
    

    }]);

提交回复
热议问题