1

所以我在 AngularJS 应用程序上实现 Angular Material Design md-autocomplete 指令。我想向控件发送一个承诺,所以如果查询没有完全加载,它不会抛出错误;并且还可以将控件中的加载栏视为“加载”的信号。

这是数据未完成加载时出现的错误:

TypeError:无法读取未定义的属性“切片”

这就是我获取数据的方式:

        $http({
            method: 'GET',
            url: $rootScope.apiURL+'getAllCustomers/'+session,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(response){
            if(response.ErrorMessage === null && response.Result !== null){
                mixpanel.track("Customers loaded for POS");
                self.customers = Object.keys(response.Result).map(function (key) {return response.Result[key]});
            }
        })
        .error(function(data){
            alert('Something went wrong. Please try again.');
            mixpanel.track("Error loading customers");
        });

这是我的html:

<md-autocomplete
        ng-disabled="ctrl.isDisabled"
        md-no-cache="ctrl.noCache"
        md-selected-item="ctrl.selectedItem"
        md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
        md-search-text="ctrl.searchText"
        md-selected-item-change="ctrl.selectedItemChange(item)"
        md-items="item in ctrl.querySearch(ctrl.searchText)"
        md-item-text="item.Name"
        md-min-length="0"
        placeholder="Buscar Cliente">
    <md-item-template>
        <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.Name}}</span>
    </md-item-template>
    <md-not-found>
        No states matching "{{ctrl.searchText}}" were found.
        <a ng-click="ctrl.newCustomer(ctrl.searchText)">Create a new one!</a>
    </md-not-found>
</md-autocomplete>

这些是处理查询的函数:

function querySearch (query) {
    var results = query ? self.customers.filter( createFilterFor(query) ) : self.customers.slice(0, 50),
        deferred;
    return results;
}

function createFilterFor(query) {
    var lowercaseQuery = angular.lowercase(query);
    return function filterFn(customer) {
        return (customer.Name.toLowerCase().indexOf(lowercaseQuery) === 0);
    };
}

谢谢!

4

1 回答 1

0

将相关代码包装成一个函数:

function foo()
  {
  return foo.self.customers.slice(0, 50);
  }

foo.self = self;

然后将语句更改为:

var results = query ? self.customers.filter( createFilterFor(query) ) : foo

并将模板中的类型检查作为三元逻辑运行:

(typeof ctrl.querySearch(ctrl.searchText) === "function") ? item in ctrl.querySearch(ctrl.searchText)() : item in ctrl.querySearch(ctrl.searchText) 

参考

于 2016-01-21T20:22:16.590 回答