laravel populating typeahead

时间:2015-11-24 12:50:00

标签: laravel laravel-5

我正在尝试使用数据列表填充typeahead。

模型:

 public function getClientNameAttribute() {
     return '{"clientID":"'.$this->id.'", "clientName": "'.$this->name.'"}';
 }

运行以下内容:

{!! $clients->lists('ClientName') !!}

我将此作为输出:

["{\"clientID\":\"1\", \"clientName\": \"client 1\"}","{\"clientID\":\"2\", \"clientName\": \"client 2\"}"

应该是这样的:

 [{"clientID": "1", "clientName": "client 1"}, {"clientID": "2", "clientName": "client 2"},

所以我需要摆脱斜线,以及每条记录周围的双引号。

<script>
            $('#client').typeahead({
    source: function (query, process) {
        client = [];
        clientid = {};
        var data = {!!$clients->lists('ClientName')!!};
        $.each(data, function (i, state) {
            clientid[state.clientName] = state;
            client.push(state.clientName);
        });
        process(client);
    },
    matcher: function (item) {
        if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
            return true;
        }
    },
    sorter: function (items) {
        return items.sort();
    },
    highlighter: function (item) {
        var regex = new RegExp('(' + this.query + ')', 'gi');
        return item.replace(regex, "<strong>$1</strong>");
    },
    updater: function (item) {
        $('#clientID').val(clientid[item].clientID);
        return item;
    }
});
        </script>

1 个答案:

答案 0 :(得分:1)

ClientName属性是双重编码的。要正确获取JSON输出,您应该修改访问器以返回数组对象而不是JSON编码的字符串:

public function getClientNameAttribute() {
     return [
          "clientID" => $this->id, 
          "clientName" => $this->name,
     ];
}