Encountered an issue with md-autocomplete: Attempting to read property 'success' of an undefined element

I encountered an issue while using Material Angular framework and md-autocomplete. The error message I receive is: Cannot read property 'success' of undefined. Below is the snippet of my code:

/*My app.js*/
var app = angular.module('app', ['ngRoute', 'ngMaterial']); //, 'ui.utils.masks'

app.config(function ($routeProvider) {
    $routeProvider
        .when('/', { controller: 'DemoCtrl', templateUrl: 'view/paginaTeste.html' })
        .otherwise({ templateUrl: '404.html' });
});

app.run(function ($rootScope) {
    $rootScope.urlServico = 'http://localhost:58999/';
});


/*My controller*/
(function () {
    'use strict';
    angular
        .module('app')
        .controller('DemoCtrl', DemoCtrl)
        .config(function ($mdThemingProvider) {
            $mdThemingProvider.theme('default')
                .primaryPalette('blue');
        });;

    function DemoCtrl($timeout, $q) {
        var self = this;

        // list of `state` value/display objects
        self.states = loadAll();
        self.selectedItem = null;
        self.searchText = null;
        self.querySearch = querySearch;

        // ******************************
        // Internal methods
        // ******************************

        /**
         * Search for states... use $timeout to simulate
         * remote dataservice call.
         */
        function querySearch(query) {
            var results = query ? self.states.filter(createFilterFor(query)) : [];
            return results;
        }

        /**
         * Build `states` list of key/value pairs
         */
        function loadAll() {
            var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
              Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
              Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
              Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
              North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
              South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
              Wisconsin, Wyoming';

            return allStates.split(/, +/g).map(function (state) {
                return {
                    value: state.toLowerCase(),
                    display: state
                };
            });
        }

        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(state) {
                return (state.value.indexOf(lowercaseQuery) === 0);
            };

        }
    }
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.0/angular-material.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic">
    <meta name="viewport" content="initial-scale=1" />
</head>
<body>

    <div layout="column" ng-view></div>

    <!-- Angular Material Dependencies -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.0/angular-material.min.js"></script>

    <script src="/view/app.js"></script>

    <script src="/view/controller/DemoCtrl.js"></script>
</body>
</html>

EDIT This is my page paginaTeste.html:

<md-content>
<form name="frmTeste">
    <section>
        <md-subheader class="md-primary">Novo Teste</md-subheader>
        <md-list layout="column" layout-padding>
            <md-item>
                <md-item-content>
                    <p>The following example demonstrates floating labels being used as a normal form element.</p>
                    <div layout-gt-sm="row">
                        <md-input-container flex>
                            <label>Name</label>
                            <input type="text" />
                        </md-input-container>
                        <md-autocomplete flex
                                         ng-disabled="DemoCtrl.isDisabled"
                                         md-no-cache="DemoCtrl.noCache"
                                         md-search-text="DemoCtrl.searchText"
                                         md-items="item in DemoCtrl.querySearch(ctrl.searchText)"
                                         md-item-text="item.display"
                                         md-floating-label="Favorite state">
                            <span md-highlight-text="DemoCtrl.searchText">{{item.display}}</span>
                        </md-autocomplete>
                    </div>
                </md-item-content>
            </md-item>
        </md-list>
    </section>
</form>

I am seeking assistance with debugging my code as I am unsure about what's causing the issue. Any help would be greatly appreciated. PS: Please excuse any errors in my English, thank you.

Thank you.

Answer №1

It appears that there may be an issue with the md-items binding in your code. Consider updating it to:

  md-items="item in DemoCtrl.querySearch(DemoCtrl.searchText)"

Additionally, it seems like you are referencing DemoCtrl.* without utilizing the Controller As syntax. You can alleviate this by modifying your route definition to:

{ controller: 'DemoCtrl', controllerAs: 'DemoCtrl', templateUrl: 'view/paginaTeste.html' }

Answer №2

I successfully resolved my issue by correcting the variable name. Here is a snippet of my updated code:

Index

<!DOCTYPE html>

<div layout="column" ng-view></div>

<!-- Angular Material Dependencies -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-messages.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.js"></script>

<script src="/view/app.js"></script>

<!--<script src="/view/angular-material.min.js"></script>-->


<script src="/view/demo-auto-complete/controller/DemoCtrl.js"></script>

App.js

var app = angular.module('app', ['ngRoute', 'ngMaterial', 'ngMessages']);

    app.config(function ($routeProvider) {
        $routeProvider
            .when('/', { controller: 'DemoCtrl', controllerAs: 'self', templateUrl: 'view/demo-auto-complete/paginaTeste.html' })
            .otherwise({ templateUrl: '404.html' });
    });

    app.run(function ($rootScope) {
        $rootScope.urlServico = 'http://localhost:58999/';
    });

DemoCtrl.js - My controller

(function () {
    'use strict';
    angular
        .module('app')
        .controller('DemoCtrl', DemoCtrl)
        .config(function ($mdThemingProvider) {
            $mdThemingProvider.theme('default')
                .primaryPalette('blue');
        });;

    function DemoCtrl($timeout, $q) {
        var self = this;

        // list of `state` value/display objects
        self.states = loadAll();
        self.selectedItem = {
            display: 'Alabama',
            value: 'alabama'
        };
        self.searchText = null;
        self.querySearch = querySearch;
        self.clearValue = clearValue;
        self.save = save;
        self.myModel = '';

        function clearValue() {
            self.myModel = undefined;
        };
        function save() {
            alert('Form was valid!');
        };

        // ******************************
        // Internal methods
        // ******************************

        /**
         * Search for states... use $timeout to simulate
         * remote dataservice call.
         */
        function querySearch(query) {
            var results = query ? self.states.filter(createFilterFor(query)) : [];
            return results;
        }

        function findValues (term, obj) {
            var deferred = this.$q.defer();
            deferred.resolve( this.$filter( 'filter' )( obj, term ) );
            return deferred.promise;
        }

        /**
         * Build `states` list of key/value pairs
         */
        function loadAll() {
            var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
              Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
              Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
              Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
              North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
              South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
              Wisconsin, Wyoming';

            return allStates.split(/, +/g).map(function (state) {
                return {
                    value: state.toLowerCase(),
                    display: state
                };
            });
        }

        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(state) {
                return (state.value.indexOf(lowercaseQuery) === 0);
            };

        }
    }
})();

paginaTeste.html - My View

<md-content>
    <form ng-submit="$event.preventDefault()" name="frmParceiroNegociosEndereco">
        <section>
            <md-subheader class="md-primary">Novo Endereço</md-subheader>
            <md-list layout="column" layout-padding>
                <md-item>
                    <md-item-content>
                        <p>The following example demonstrates asdasdasda floating labels being used as a normal form element.</p>
                        <div layout-gt-sm="row">
                            <md-input-container flex>
                                <label>Name</label>
                                <input type="text" />
                            </md-input-container>
                        <md-autocomplete flex
                                             md-input-name="autocompleteField"
                                             md-no-cache="self.noCache"
                                             md-selected-item="self.selectedItem"
                                             md-search-text="self.searchText"
                                             md-items="item in self.querySearch(self.searchText)"
                                             md-item-text="item.display"
                                             md-floating-label="Favorite state">
                                <md-item-template>
                                    <span md-highlight-text="self.searchText">{{item.display}}</span>
                                </md-item-template>
                            </md-autocomplete>
                        </div>
                        <h1>Teste</h1>
                    </md-item-content>
                </md-item>
            </md-list>
        </section>
    </form>
</md-content>

I am glad I could assist someone, and I appreciate the help received from others.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Is it possible to pass an HTML element's id attribute to a function in JavaScript?

In the following code snippet, I am looking to send the id=content to the function mr and then display the result in the passed id=result. While this functionality is currently limited to this HTML file, I aim to extend it to other HTML pages by adding the ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...

The like button seems to be malfunctioning and I'm not sure what the issue is

I've added the ability for users to like my posts, but it's not working as intended. Here's the code snippet I used: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=Tru ...

Eliminate screen flickering during initial page load

I've been developing a static website using NuxtJS where users can choose between dark mode and default CSS media query selectors. Here is the code snippet for achieving this: <template> <div class="container"> <vertical-nav /> ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

Html5Mode - solving the problem of page refreshing in angularjs

I've been developing an angularJS app that utilizes URLs in the following format during development: http://localhost:6001/#/home/index http://localhost:6001/#/content/index Since I plan for the app to be accessible on desktop browsers as well, I wa ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

Checking variable length time with JavaScript Regular Expression

My specific requirement is to validate a string ranging from 1 to 4 characters in length (where H stands for hour and M represents minutes): If the string has 1 character, it should be in the format of H (a digit between 0-9). A 2-character string should ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...

The error code 13:5 indicates that the "Home" component has been registered in the Vue application but is not being used, leading to the error message "vue/no-unused-components"

I encountered this issue while working with Vue for the first time. I was attempting to construct a website using Vue/CLI by reorganizing and building from the inside out. However, I am unfamiliar with Vue and unsure how to resolve this error. The changes ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

Is there a way to retrieve multiple results by utilizing fetch and randomuser.me?

I am currently working with the randomuser.me API and have set up the fetch request correctly. My goal is to retrieve 5 users separated by commas instead of just one. As mentioned in randomuser.me's documentation, I simply need to append the fetch UR ...

Automatically compute and convert currency formats using JavaScript

May I ask again? Hopefully you understand. I am looking to automatically calculate with a money format. Here is a demo: https://jsfiddle.net/xp4ky2gg/ This is my code... HTML code <table style="width:100%"> ...

How can I make sure a Post method finishes executing before returning the result of a Get method in Express.js?

I am currently utilizing the Ionic framework and Express to facilitate communication between my application, a server API, and a JavaScript game. The game transmits information to the API through XMLHttpRequest and post requests, while my application retri ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

AngularJS and Ionic Framework - Click on a specific row to interact with it

I am struggling to open a new page when an item is touched in my HTML code. Despite trying multiple times, I can't seem to make it work and I'm at a loss as to why. Below is the snippet of my HTML: <!DOCTYPE html> <html> <hea ...