Search code examples
angularjsangularjs-directiveangularjs-service

Error in LInking service and directive in Angular


I have an issue at linking service having http to a directive. This is the code of that...

    myapp.factory ( 'autoCompleteDataService', ['$http', function($http) {
   return {
       getSource: function(callback) {
          var url = 'get_data_from_server.php';
          $http.get(url).success(function(data) {
             callback(data);
          });
       }
   }
} ] );

myapp.directive('autoComplete', function(autoCompleteDataService) {
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            elem.autocomplete({
                source: autoCompleteDataService.getSource(), 
                select: function( event, ui ) {
                         scope.$apply(function() {
                           scope.item.unit_id = ui.item.value; 
                         });
                        },
                minLength: 2
            });
        }
    };
});

I replaced callback(data); with return data; with no result...

Any help is appreciated..

Edit: added working code without http

If I keep this code instead the above one its working

myapp.factory('autoCompleteDataService', [function() {
return {
    getSource: function() {
        return ['apples', 'oranges', 'bananas'];
    }
}

}]);


Solution

  • myapp.factory('autoCompleteDataService', ['$http', function($http) {
        return {
            getSource: function() {
                var url = 'get_data_from_server.php';
                return $http.get(url);
            }
        }
    }]);
    

    Directive:

    link : function(scope, elem, attr, ctrl) {
        autoCompleteDataService.getSource().success(function(data) {
            elem.autocomplete({
                source: data, 
                select: function( event, ui ) {
                    scope.$apply(function() { scope.item.unit_id = ui.item.value; });
                },
                change: function (event, ui) {
                    if (ui.item === null) {
                        scope.$apply(function() { scope.foo = null });
                    }
                },
                minLength: 2
            });
        });
    }