Error in AngularJS Controller: Unable to assign value to property 'query' since it is undefined

I am a beginner with Angular and I'm trying to initialize a variable query as null and imgType as "illustration" in my controller. However, I keep getting an error:

Uncaught TypeError: Cannot set property 'query' of undefined".

Any idea what could be causing this issue? Everything else seems to be working fine.

My AngularJS version is 1.4.3

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body ng-app="ilustracka">
        <!--Controller-->
        <div ng-controller="SearchController as searchCtrl" ng-cloak>
            <!--Searching-->
            <form ng-submit="searchCtrl.search()"> 
                <input type="text" ng-model="searchCtrl.query" placeholder="search...">
                <select ng-model="searchCtrl.imgType">
                    <option value="illustration" selected>ILU</option>
                    <option value="image">IMG</option>
                </select>
                <button type="submit">SEARCH</button>
            </form>

            <!--Summary result--
            <summary></summary>-->

            <!--Result-->
            <output></output>      
        </div>

        <!--JavaScripts-->  
        <script src="libs/angularjs/angular.min.js"></script>
        <script src="scripts/ilustracka.js"></script>
        <script src="scripts/searchController.js"></script>
        <script src="scripts/outputDirective.js"></script>
        <script src="scripts/searchApiService.js"></script>        
    </body>
</html>

Controller

(function () {
    'use strict';

    angular
        .module('ilustracka')
        .controller('SearchController', SearchController);

    //load service searchApi
    SearchController().$inject['searchApi'];

    function SearchController(searchApi) {
        var vm = this;
        /*
         * vars
         */
        vm.query = null;//search string
        vm.imgType = 'illustration';//type of search image - (ilu|img)
        vm.images = null;//result of query - empty object
        vm.result = null;//showing result or info message
        /*
         * functions
         */
        vm.search = search;


        function search(){
            //!empty searchQuery
            if(vm.query){
                searchApi.searchImg(vm.query, vm.imgType); 
                vm.images = searchApi.getImages();
                vm.result = searchApi.getResult();
            }            
        }   
    }
}());

ilustracka

(function(){
    "use strict";   
    angular
            .module("ilustracka", []);
}());

Answer №1

The issue lies in how the searchApi service is injected into your controller. The correct syntax for using $inject is as follows:

SearchController.$inject = ['searchApi'];

In your original code snippet,

SearchController().$inject['searchApi'];
, you encountered an unhandled error because SearchController() resulted in undefined, and this undefined value does not have a property of $inject. This led to further errors related to unknown providers due to missing dependency injection, ultimately preventing the proper instantiation of the controller.

Answer №2

//Make sure to define your app module with a dependency array, whether it is empty or not. angular.module('ilustracka', []) //include empty brackets

http://jsbin.com/riyozu/edit?html,js,output

   (function () {
  'use strict';
  angular
    .module('ilustracka', [])
    .controller('SearchController', ['searchAPi', function (searchApi) {
      var vm = this;
      vm.query = null;//enter search query here
      vm.imgType = 'illustration';//choose image type - (ilu|img)
      vm.images = null;//store query results - empty object initially
      vm.result = null;//display result or info message
      function search() {
        if (vm.query) {
          searchApi.searchImg(vm.query, vm.imgType);
          vm.images = searchApi.getImages();
          vm.result = searchApi.getResult();
        }
      }
      vm.search = search;
    }]);
}());

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

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Leave your thoughts with HTML and Javascript coding

Currently, I am working on developing a comment box feature using HTML and JavaScript. I have encountered a question regarding how to implement a delete functionality for comments using a button. Would it be more efficient to utilize a linked list struct ...

Dynamically Returning Multiple Functions in Javascript: A Comprehensive Guide

I apologize if my question was unclear. Let me explain the issue I am facing. I am currently working on implementing a search functionality in a table, where users can search in specific columns. Currently, I am manually checking which checkboxes are sel ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

Ways to efficiently insert a single element into an array multiple times simultaneously

Can you please help me improve my function that displays the number of coins corresponding to a certain value? For example, an input of 56 should return [25, 25, 5, 1]. I am facing two challenges: 1) How can I display multiple instances of the same coin i ...

Display data from two arrays in real-time

The following data is available: "PensionPlanSummary": [ { "Type": "DefinedContributionPension", "Participants": [ { "Year": 2018, "Value": 425.0 } ...

Utilizing API data sharing across AngularJS controllers

I am facing a challenge with my parent controller and its children controllers, as I want them all to share the data fetched from an Api service. Controllers: var app = angular.module('mymodule',[]); app.controller('main', ['$scop ...

Adding a link to a specific word in text using JavaScript or PHP

I am seeking a solution for how to automatically add a link to a specific word in text using PHP or JS. For instance: I want to insert a link for each occurrence of the word "lorem" in the text. such as: <a href=https://wwww.google.com/>lorem</ ...

A service is unable to locate a dependency due to the injection of another service

I am encountering an issue in my NestJs application where a previously functional service is now throwing an error (ReviewService can't find DoctorLoaderService) after I implemented dependency injection on two other services (PmsConnectionService -> ...

Enabling the use of placeholder text with jQuery

I successfully implemented code to set placeholder values for username and password fields: <script>document.getElementById("user_login").setAttribute("placeholder","Please enter your Email Address");</script> and <script>document.getE ...

Interactive Event Coordinator

Can a JavaScript script be executed in a specific way until a pop-up element is visible, without relying on setTimeout()? Here are the steps for when the pop-up appears: A user is browsing abc.com and clicks on a button. The pop-up element then shows up ...

What is the best method for eliminating a specific line from numerous HTML pages?

I have a series of HTML pages, each with a line at the top that reads: <?xml version="1.0" encoding="UTF-8" ?> When I was working on localhost, the pages opened without any issue. However, now that I have uploaded the files to the server, I am enco ...

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

What is causing the turn.js demo to not function properly?

I tested the demo script on fiddle as recommended in the official docs. Upon downloading the script and trying to run it in my browser, I encountered a problem where it did not work, and no errors were displayed on the console. Curiously, when I ran the ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

Add a file to your Google Drive by utilizing AJAX with Google Apps Script

Currently, I am working on a code to upload an image file to Google Drive using app script. I have encountered an issue where I am unable to retrieve the file from the request.parameters. I attempted to use formData as well, but it did not resolve the pro ...

Basic mathematical operation utilizing a JQuery duplication event

Every time a new row is created, I want txtA divided by txtB to equal txtC. Please input the solution for textfield C. <table> <tr> <td><input type="text" id="txtA" name="txtA"></td> <td><input type="text" id ...

Top method for performing data interpolation in Angular 4 and above

I have a concern regarding data interpolation in Angular. For instance, when I need to display a value returned from a function in the UI, my approach is usually as follows: In my TypeScript file: public getUserName() { return 'Arpit'; } ...

Oops! The useNavigate() function can only be utilized within the confines of a <Router> component

I encountered an error while working on my project: An uncaught Error occurred: useNavigate() may only be used within a context of a <Router> component. at invariant (bundle.js:36570:20) at useNavigate (bundle.js:36914:35) at App (bundle. ...

Building validation in AngularJS with ng-messages without requiring a form control

In my database/model, I store time as an integer representing minutes. But for the user interface, I want to present it in decimal hours and allow them to edit it using buttons. I currently have the following setup: <p class="input-group"> < ...