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

How do useCases interact with each other within Clean Architecture principles in NodeJS?

I'm currently working on implementing Bob Martin's Clean Architecture in my project, and I have a question. How do use-cases interact with each other? For instance: In my project, there are entities for Department and Employee. The Department ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

The AngularJS ngResource factory returns a function instead of a promise, providing a unique method for

Currently, I am working on developing an Angular factory that involves manipulating two sets of data. My objective is to make one set of data equal to a variable so that it can be passed in another API call. However, I'm encountering an issue where th ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Troubleshooting: Jquery Toggle Issue When Used with Adjacent Div Element

I've been puzzling over this issue for hours now. The intention of this code is to display a div, but it's just not cooperating. <div id="butbr"> <div id="sup_nav"> <div id="stup" class="bxt1"></div> <div id= ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...

Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below: "data":[ ["1951","306","27","159","34","82","4"], ["1956","426","41","203","47","119","16"], ["1959","562","67"," ...

Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error referenceError: items is not defined. Can anyone help me figure out why this error is occurring or provide some guidance? Upon initial inspection of the code, it seems like the issue may be rel ...

Is it necessary for each React component to have its own individual stylesheet?

Looking for some advice on React as a newbie here. I'm wondering whether each React component should have its own stylesheet. For instance, if I have my main App component that gets rendered to the browser, is it sufficient to include a CSS file the ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...