I am not able to use angularjs md-autocomplete directive. Please let me know where is the issue.
TypeError: Cannot read property 'then' of undefined
at de (angular-material.min.js:13)
at he (angular-material.min.js:13)
at e.B [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:415)
at b (angular.min.js:125)
at e (angular.min.js:272)
at b.$eval (angular.min.js:144)
at b.$apply (angular.min.js:145)
at HTMLInputElement.<anonymous> (angular.min.js:272)
I get this error when I opens md-autocomplete
TypeError: Cannot read property 'filter' of undefined
at DeliveryCtrl.querySearch (DeliveryCtrl.js:81)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:416)
at b (angular.min.js:125)
at n.$eval (angular.min.js:144)
at de (angular-material.min.js:13)
at he (angular-material.min.js:13)
at e.B [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:415)
at b (angular.min.js:125)
at e (angular.min.js:272)
here is my controller
(function() {
'use strict';
RLabs.controller('DeliveryCtrl', DeliveryCtrl);
function DeliveryCtrl($timeout, $q, $log, $http, $scope, resto_info, base_url) {
$scope.delivery_areas = [];
$scope.fun1 = function() {
$scope.fun2().then(function(data) {
console.log("after call to fun2"); // execute before fun2
var myArray = data;
var myString = JSON.stringify(myArray.join(', '));
console.log(myString);
console.log(myArray);
return myString.split(/, +/g).map(function(state) {
return {
value: state.toLowerCase(),
display: state
};
});
});
}
$scope.fun2 = function() {
var deferred = $q.defer();
$http({
url: base_url.base_url + 'profile-load',
method: "POST",
data: {
"profile_id": resto_info.profile_id,
"api_key": resto_info.api_key,
"app_version": resto_info.app_version,
"request_operation": "get_delivery_area_data"
}
}).success(function(response) {
console.log(response);
console.log(response.response.location[0].delivery.areas);
$scope.delivery_areas = response.response.location[0].delivery.areas;
console.log($scope.delivery_areas);
deferred.resolve(response.response.location[0].delivery.areas);
}).error(function() {
deferred.resolve(null);
});
return deferred.promise;
}
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.states = $scope.fun1();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
alert("Sorry! You'll need to create a Constitution for " + state + " first!");
}
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function() {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
}})();
and here is my html
<div ng-controller="DeliveryCtrl as ctrl" layout="column" ng-cloak>
<md-content class="md-padding">
<form ng-submit="$event.preventDefault()">
<p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p>
<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.display" md-min-length="0" placeholder="What is your favorite US state?">
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
<br/>
<md-checkbox ng-model="ctrl.simulateQuery">Simulate query for results?</md-checkbox>
<md-checkbox ng-model="ctrl.noCache">Disable caching of queries?</md-checkbox>
<md-checkbox ng-model="ctrl.isDisabled">Disable the input?</md-checkbox>
<p>By default, <code>md-autocomplete</code> will cache results when performing a query. After the initial call is performed, it will use the cached results to eliminate unnecessary server requests or lookup logic. This can be disabled above.</p>
</form>
</md-content>
please provide me the solution how to get the value of myString in the autocomplete directive select list
i had the same issue, this works for me:
function autoComplete(query) {
if (!query || query.length < 2) {
return vm.complete = [];
}
// http request
}
Related
After executing the list in md-autoComplete. I am getting this error while searching. I have given controller name as ctrl and included the $timeout, $q, $log, attaching html and js file.
Please let me know how to fix it. Thanks in advance.
error
ionic.bundle.js:26794 TypeError: Cannot read property 'indexOf' of
null
at filterFn (http://localhost:8100/js/guest-controller.js:102:31)
at Array.filter (native)
at Object.querySearch (http://localhost:8100/js/guest-
controller.js:60:41)
at fn (eval at compile
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:27638:15),
<anonymous>:4:344)
at Scope.$eval
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:30395:28)
at de
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:11563)
at he
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:12420)
at
https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:8834
at processQueue
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:29127:28)
html file
<div class="form_element_grid auto_fill_info">
<label>Company Name</label>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="true"
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.display"
md-min-length="0"
placeholder="Enter Company Name" required/>
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
Js file
var self = this;
$scope.guestDetails = guestData.data;
self.searchText = '';
self.simulateQuery = false;
self.isDisabled = false;
// list of `state` value/display objects
self.states = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
self.states= loadAll();
}
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.states.filter( createFilterFor(query)
) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); },
Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `states` list of key/value pairs
*/
function loadAll() {
var deliverycomp = $scope.guestDetails;
console.log(deliverycomp);
return deliverycomp.map( function (state) {
return {
value: state.guestId,
display: state.guestName
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = query;
return function filterFn(state) {
return (state.display.indexOf('lowercaseQuery') === 0);
};
}
i am using angular material autocomplete.i am getting error when click on the autocomplete text box.
TypeError: Cannot read property 'then' of undefined
at me (angular-material.min.js:13)
at ve (angular-material.min.js:13)
at e.q [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.js:15152), <anonymous>:4:295)
at e (angular.js:26673)
at b.$eval (angular.js:17958)
at b.$apply (angular.js:18058)
at HTMLInputElement.<anonymous> (angular.js:26678)
at HTMLInputElement.dispatch (jquery.min.js:3)
at HTMLInputElement.r.handle (jquery.min.js:3)
here is my controller.
(function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$location', '$rootScope', '$scope', '$mdMedia', '$mdDialog'];
function MenuController($location, $rootScope, $scope, $mdMedia, $mdDialog) {
$scope.headtext = "This is header";
function initController() {
}
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
// ******************************
// Internal methods
// ******************************
/**
* Search for repos... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.repos.filter( createFilterFor(query) ) : self.repos,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `components` list of key/value pairs
*/
function loadAll() {
var repos = [
{
'name' : 'Angular 1',
'url' : 'https://github.com/angular/angular.js',
'watchers' : '3,623',
'forks' : '16,175',
},
{
'name' : 'Angular 2',
'url' : 'https://github.com/angular/angular',
'watchers' : '469',
'forks' : '760',
},
{
'name' : 'Angular Material',
'url' : 'https://github.com/angular/material',
'watchers' : '727',
'forks' : '1,241',
},
{
'name' : 'Bower Material',
'url' : 'https://github.com/angular/bower-material',
'watchers' : '42',
'forks' : '84',
},
{
'name' : 'Material Start',
'url' : 'https://github.com/angular/material-start',
'watchers' : '81',
'forks' : '303',
}
];
return repos.map( function (repo) {
repo.value = repo.name.toLowerCase();
return repo;
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
})();
This is my html
<md-content layout-padding layout="column">
<form ng-submit="$event.preventDefault()">
<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="Pick an Angular repository"
md-menu-class="autocomplete-custom-template">
<md-item-template>
<span class="item-title">
<md-icon md-svg-icon="img/icons/octicon-repo.svg"></md-icon>
<span> {{item.name}} </span>
</span>
<span class="item-metadata">
<span class="item-metastat">
<strong>{{item.watchers}}</strong> watchers
</span>
<span class="item-metastat">
<strong>{{item.forks}}</strong> forks
</span>
</span>
</md-item-template>
</md-autocomplete>
</form>
</md-content>
i cannot trace this error please help.
You're not instantiated the selected items.
self.selectedItem = [];
I used md-autocomplete inside html form, then I wanted to set its field to empty after submitting. I tried, as shown in the snippet, to use $setPristine() but it didn't work. I also tried to assign the model to null or empty string, but also it wasn't successful.
PS: Angularjs version I used is v1.3.15
angular.module("myApp", ["ngMaterial"])
.controller("main", function($scope){
$scope.searchString = "";
$scope.routeToSearchPage = function (searchString, form) {
$scope.form.$setPristine();
};
$scope.simulateQuery = false;
$scope.isDisabled = false;
$scope.states = loadAll();
$scope.querySearch = querySearch;
function querySearch (query) {
var results = query ? $scope.states.filter( createFilterFor(query) ) : $scope.states,
deferred;
if ($scope.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function loadAll() {
var allStates = "aaa, bbbb, cccc, bla";
return allStates.split(/, +/g).map( function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-aria.js"></script>
<script src="//rawgit.com/angular/bower-material/master/angular-material.js"></script>
<div ng-app="myApp">
<div ng-controller="main">
<form name="form"
ng-submit="submit(searchString);$event.preventDefault();">
<md-autocomplete
md-floating-label="search"
ng-disabled="isDisabled"
md-no-cache="noCache"
md-selected-item="selectedItem"
md-search-text="searchString"
md-items="item in querySearch(searchString)"
md-item-text="item.display"
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">
<md-item-template>
<span md-highlight-text="searchString" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
</md-autocomplete>
</form>
<md-button ng-click="routeToSearchPage(searchString, form)">
<md-icon class="material-icons">search</md-icon>
</md-button>
</div>
</div>
Here's an example of clearing an md-autocomplete - CodePen
Your snippet isn't actually showing the md-autocomplete as it should appear.
JS
$scope.clear = function () {
$scope.searchString = null;
};
I have also removed the markup below for the CodePen to work correctly:
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">
I using md-autocomplete in my page, Now I need to edit a record, how to change selected value in md-autocomplete programmatically?
This is angular code:
app.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q, $log) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.states = loadAll();
self.querySearch = querySearch;
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) != -1);
};
}
function loadAll() {
return totlaTablaeau.map(function (repo) {
repo.value = repo.address.toLowerCase();
return repo;
});
}
};
Here's a CodePen using the online docs example. You just need to set the value of md-selected-item.
Markup
<md-autocomplete ... md-selected-item="ctrl.selectedItem" ...></md-autocomplete>
...
<md-button class="md-raised md-primary" ng-click="ctrl.selectArkansas()">Select Arkansas</md-button>
JS
self.selectArkansas = function() {
self.selectedItem = {
value: "Arkansas".toLowerCase(),
display: "Arkansas"
};
}
Your Html template looks like this.
<md-autocomplete
md-selected-item="model"
md-search-text="search_text"
md-items="item in searchResults()"
md-item-text="item.title"
md-min-length="3"
md-floating-label="Your Label"
placeholder="placeholder"
>
<md-item-template>
<span> {{item.title}},{{item.name}}</span>
</md-item-template>
<md-not-found>
No matches found.
</md-not-found>
</md-autocomplete>
Your controller code
class Controller {
constructor($service) {
this.$service = $service;
}
//we are init the varible hare.
$onInit() {
this.search_text = "";
//set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};
}
}
//function for get data list
// $service this is service function we can define in over services file and we can inject this way
searchResults() {
let { $service, search_text } = this;
return $service.search(search_text).then((data) =>data.list).catch(err =>{ });
}
//Responce data look like this
//[{id:'00h1',title:'test1',name:'harish verma'},
//{id:'00h2',title:'test1',name:'harish verma'},
//{id:'00h3',title:'test1',name:'harish verma'},
//{id:'00h4',title:'test1',name:'harish verma'}];
}
Controller.$inject = [
"Service"
];
export default Controller;
set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};
Trying to get the factory (below) to retrieve a json file. Do you know what is wrong? (Angular v.1.3.x-beta)
HTML
<div class="search">
<input type="text" ng-model="query" ng-model-options="{debounce:750}" ng-change="updateSearch()"/>
</div>
{{results | json}}
JS
directory.controller('DirectorySearchController', function($scope, searchFactory) {
$scope.updateSearch = function() {
$formatted = $scope.query.replace(/\s{1,}/g, '+');
if($scope.query != '') {
$scope.results = searchFactory.simpleSearch($formatted);
} else {
$scope.results = '';
}
};
});
directory.factory('searchFactory', function($http) {
var urlBase = 'http://example.com/api';
var searchFactory = {};
searchFactory.simpleSearch = function (keyword) {
return $http.get(urlBase + '/search/' + keyword);
};
return searchFactory;
});
Looking at your code the factory returns a promise, and automatic promise unwrapping is not available in new versions of angular. Try this
searchFactory.simpleSearch($formatted).success(function(data){
$scope.results=data;
});