Не удается прочитать свойство ‘then’ undefined с использованием автозаполнения Angular Material

#javascript #angularjs #angular-material

#javascript #angularjs #angular-material

Вопрос:

У меня есть такой код:

 <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}} amp;<{{item.email}}amp;></span>
    </md-autocomplete>
</body>
  

и 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;
  };
});
  

и я получил это исключение, когда я что-то печатаю, что не так с моим кодом.

 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}} amp;<{{item.email}}amp;></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.
-->  

Вот CodePen

Ответ №1:

простая ошибка. Добавить ng-controller="main"