2014-11-06 89 views
0

我想为我的REST控制器使用一个工厂,该工厂返回一个字符串数组。我想在我的services.js中重用这个函数。

这是我的HTML(自动填充的输入域)

<input type="text" ng-model="vertrag.vertrag.v00Lobcode.lobCode" typeahead-wait-ms="1000" 
typeahead="lobcode for lobcode in getLobcode($viewValue)" typeahead-loading="loadingLobcodes"> 

控制器

$scope.getLobcode = function(val) { 
    Autocomplete.get(val).then(function(promise) { 
     console.log(promise); 
    }); 
}; 

services.js

AppServices.factory('Autocomplete', function($http, API_URL) { 
return { 
    get: function(val) { 
     var promise = $http.get(API_URL+'/leistobjekts/autocomplete/'+val.toUpperCase()) 
      .then(function(response) { 
       return response.data; 
     }); 
     return promise; 
    } 
}; 

});

我的异常

TypeError: Cannot read property 'length' of undefined 
at http://localhost:8080/bootstrap/js/ui-bootstrap-tpls-0.11.0.js:3553:24 
at deferred.promise.then.wrappedCallback (http://localhost:8080/js/lib/angular/angular.js:11498:81) 
at deferred.promise.then.wrappedCallback (http://localhost:8080/js/lib/angular/angular.js:11498:81) 
at http://localhost:8080/js/lib/angular/angular.js:11584:26 
at Scope.$get.Scope.$eval (http://localhost:8080/js/lib/angular/angular.js:12608:28) 
at Scope.$get.Scope.$digest (http://localhost:8080/js/lib/angular/angular.js:12420:31) 
at Scope.$get.Scope.$apply (http://localhost:8080/js/lib/angular/angular.js:12712:24) 
at http://localhost:8080/js/lib/angular/angular.js:14220:36 
at completeOutstandingRequest (http://localhost:8080/js/lib/angular/angular.js:4349:10) 
at http://localhost:8080/js/lib/angular/angular.js:4650:7 

其实我回来,我需要正确的结果(控制台),但错误说什么不正常。自动完成功能没有显示任何内容。

这是我已经为我工作的自动完成功能。但它不是真正可重用的。

$scope.getLobcode = function(val) { 
    return $http({ 
     method: "GET", 
     url: API_URL+'/leistobjekts/autocomplete/'+val.toUpperCase(), 
     cache:true 

    }).then(function(res){ 
     console.log(res.data); 
     var lobcodes = []; 
     angular.forEach(res.data, function(item){ 
      lobcodes.push(item); 
     }); 
      return lobcodes; 
     }); 
}; 

在此先感谢。

回答

2

返回你的承诺是这样的:

$scope.getLobcode = function(val) { 
    return Autocomplete.get(val); 
}; 

或简单地做到这一点:

$scope.getLobcode = Autocomplete.get; 
相关问题