angularjsangular-materialmd-autocomplete

User object to populate md-items in md-autocomplete


I want to populate my md-autocomplete with an object containing user objects. It's retrieved in JSON format through a factory into $scope.users. I can check the object in my console using an Angular viewer.

users:
    user_id:
        display_name: "value"
        first_name: "value"
        last_name: "value"
    user_id:
        display_name: "value"
        first_name: "value"
        last_name: "value"
    etc...

I want the model value to be set to the user_id model and the display text to be display_name. Is this possible? I have tried (according to the documentation only the md-items attribute should be required

<md-autocomplete md-items="u in users"></autocomplete>

But it doesn't do anything. Neither does following the "basic example"

<md-autocomplete md-selected-item="videoInfo.lineUp.1" md-search-text="looseheadSearchText" md-items="u in users" md-item-text="u.display_name"></md-autocomplete>

EDIT

Here's the code I use to get my users object:

angular.module("app").controller("MainController", ["$scope", "userRepository", function ($scope, userRepository) {
    userRepository.get(function(data) {
        $scope.users = data;
    });

app.factory("userRepository",
    function($resource) {
        return $resource("/wp-content/themes/zerif-lite-child/inc/get_users.php");
    });

Solution

  • HTML:

    <md-autocomplete
        md-selected-item="videoInfo.lineUp[1]"
        md-search-text="searchText"
        md-items="item in searchQuery(searchText)"
        md-item-text="item.display">
    </md-autocomplete>
    

    Angular searchQuery() function:

    $scope.searchQuery = function (searchText) {
        var query = searchText.toLowerCase();
        var users = [];
        angular.forEach($scope.users,
            function (value, key) {
                // value = user object
                // key = userId
                var dN = value["display_name"];
                if (dN) {
                    var obj = {};
                    obj[key] = value;
                    obj["display"] = dN;
                    if (dN.toLowerCase().indexOf(query) !== -1) {
                        users.push(obj);
                    }
                }
            });
        return users;
    }