1

我在将具有 http 的服务链接到指令时遇到问题。这是那个的代码...

    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
            });
        }
    };
});

我换成callback(data);没有return data;结果...

任何帮助表示赞赏..

编辑:添加了没有 http 的工作代码

如果我保留此代码而不是上面的代码,则它可以正常工作

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

}]);

4

2 回答 2

1

解决问题的另一种方法是,在服务器端使用完整的过滤逻辑..

    myapp.directive('autoComplete', function(autoCompleteDataService) {
    return {
        restrict: 'A',

        link: function(scope, elem, attr, ctrl) {

            elem.autocomplete({

                source: function( request, response ) {
                            $.ajax({
                              url: "./get_data_from_server.php",
                              dataType: "json",
                              data: {
                                maxRows: 10,
                                startsWith: request.term
                              },
                              success: function( data ) {
                                  response(data);
                              }
                            });
                          },

                select: function( event, ui ) {
            scope.$apply(function() { scope.item.unit_id = ui.item.value; });
                },

                minLength: 2
            });
        }

    };
 });
于 2013-09-26T11:03:43.490 回答
0
myapp.factory('autoCompleteDataService', ['$http', function($http) {
    return {
        getSource: function() {
            var url = 'get_data_from_server.php';
            return $http.get(url);
        }
    }
}]);

指示:

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
        });
    });
}
于 2013-09-26T07:19:19.080 回答