jcubic jcubic - 2 months ago 67
AngularJS Question

Cannot read property 'then' of undefined using Angular Material autocomplete

I have code like this:

<body layout="row" ng-app="myApp" controller="main" ng-cloak>
<md-autocomplete md-items="item in search(searchText)"
md-search-text="searchText"
md-item-text="item.name"
md-selected-item="selectedUser"
md-no-cache="true"
md-floating-label="Enter user ID or email address">
<md-item-template>
<span md-highlight-text="searchText">{{item.name}} {{item.surname}} &lt;{{item.email}}&gt;</span>
</md-autocomplete>
</body>


and js:

var app = angular.module('myApp',['ngMaterial']);
app.controller('main', function($scope, $q, $timeout) {
var items = [
{
userId: 10,
name: 'Foo',
surname: 'Bar',
email: 'email@example.com'
}
];
$scope.search = function(search) {
console.log('search');
var deferred = $q.defer();
$timeout(function() {
deferred.resolve(items);
}, Math.random() * 500, false);
return deferred.promise;
};
});


and I got this exception when I type something, what's wrong with my code.



var app = angular.module('myApp',['ngMaterial']);
app.controller('main', function($scope, $q, $timeout) {
var items = [
{
userId: 10,
name: 'Foo',
surname: 'Bar',
email: 'email@example.com'
}
];
$scope.search = function(search) {
console.log('search');
var deferred = $q.defer();
$timeout(function() {
deferred.resolve(items);
}, Math.random() * 500, false);
return deferred.promise;
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body layout="row" ng-app="myApp" controller="main" ng-cloak>
<md-autocomplete md-items="item in search(searchText)"
md-search-text="searchText"
md-item-text="item.name"
md-selected-item="selectedUser"
md-no-cache="true"
md-floating-label="Enter user ID or email address">
<md-item-template>
<span md-highlight-text="searchText">{{item.name}} {{item.surname}} &lt;{{item.email}}&gt;</span>
</md-autocomplete>
</body>

<!--
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be in foundin the LICENSE file at http://material.angularjs.org/license.
-->





Here is CodePen

Answer

simple mistake. Add ng-controller="main"