md-autocomplete不会等待服务中的数据。怎么解决?

时间:2016-04-14 13:13:14

标签: javascript html angularjs md-autocomplete

我想构建一个md-autocomplete,但我无法显示选项。始终显示只有在没有插入输入选项时才应启动的错误消息 我的服务正确返回,我的控制器只在收到服务数据后返回。

HTML:

<md-autocomplete placeholder="Postal-Code"
                 md-selected-item="selectedItem" 
                 md-no-cache="true"
                 md-search-text="searchText" 
                 md-items="item in welcomeScope.getPostalCode(searchText)"
                 md-item-text="item.cp4Code">
  <md-item-template>
    <span md-highlight-text="searchText">{{item.cp4Code}}</span>
  </md-item-template>
  <md-not-found>
    ERROR
  </md-not-found>
</md-autocomplete>

控制器:

welcomeScope.getPostalCode = function (key){
   welcomeSvc.getAllPostalCodes(key).then(function(data){
   return data.result.returnvalue;
});  

服务:

var getAllPostalCodes = function(key){
        return Restangular.all(...).post(JSON.stringify()).then(function(response){
            var obj = angular.fromJson(response);
            if (!obj.isError) {
                return obj;
            }
            else{
                console.log("ERROR!");
            }
        });
};

控制器中返回的示例结果是:

[  
  {"id":00001,"cp4Code":"1000","cp3Code":"111","postalDesignator":"aaaaa"},  
  {"id":00002,"cp4Code":"1000","cp3Code":"112","postalDesignator":"bbbbb"},  
  ...      
]

1 个答案:

答案 0 :(得分:0)

welcomeScope.getPostalCode没有返回值,从promise内部返回并不会影响外部函数。缩进使这更加清晰,像这样:

welcomeScope.getPostalCode = function (key){
    welcomeSvc.getAllPostalCodes(key).then(function(data){
        return data.result.returnvalue;
    });
};

如果您未从welcomeSvc.getAllPostalCodes返回承诺,则md-autocomplete无法获得结果。

welcomeScope.getPostalCode = function (key){
    return welcomeSvc.getAllPostalCodes(key).then(function(data){
        return data.result.returnvalue;
    });
};