Creating an AngularJS directive with the help of the angular.module function

Could someone please help me understand why I am getting an "Argument 'MainCtrl' is not a function, got undefined" error? It seems to be related to module dependency injection when using directives.

angular.module('app', [])
  .controller('MainCtrl', [function() {
    var self = this;
    self.name = "will this work";
    self.items = [
      {
        name: "name 1",
        test: "test 1"
      },
      {
        name: "name 2",
        test: "test 2"
      }
    ];
  }]);

angular.module('app',[])
  .directive('typeahead', [function() {
    return {
      templateUrl: 'type-ahead.html',
      restrict: 'AEC',
      scope: {
        items: '=',
        prompt: '@',
        title: '@',
        subtitle: '@',
        model: '=',
        onSelect: '&'
      }, <...more code>

However, everything works fine if I remove the

[ ]

module dependency brackets from the directive declaration like this:

angular.module('app').directive('typeahead', ...)

Alternatively, it also works if I define the directive after the controller like this:

angular.module('app', [])
      .controller('MainCtrl', [function() {
        var self = this;
        self.name = "will this work";
        self.items = [
          {
            name: "name 1",
            test: "test 1"
          },
          {
            name: "name 2",
            test: "test 2"
          }
        ];
      }])

    .directive('typeahead', [function() {
        return {

Thank you in advance for any assistance!

Answer №1

Encountering the Dilemma of Creation versus Retrieval in Angular:

It is important to note that when you use angular.module('myModule', []), a new module named myModule will be created and any existing module with the same name will be overwritten. To retrieve an existing module, you should use angular.module('myModule').

The first time you execute angular.module('app',[]), Angular will create a module called app. Subsequent executions only require angular.module('app') to load the existing module app.

By calling angular.module('app',[]) once more, the module app has been re-initialized, resulting in MainCtrl being undefined at this point.

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 are the benefits of refraining from calling functions in AngularJS views to showcase data in a more objective manner?

In our work application, we have a function that generates various objects inheriting methods from a prototype. To summarize, this function creates instances of the MileCounter object. Here is an example: function MileCounter(totalMilesRan, numOfDaysToRu ...

Is it possible to utilize MongooseArray.prototype.pull() in typescript?

A problem has arisen in Typescript at this specific line of code: user.posts.pull(postId); An error message I'm encountering states: Property 'pull' does not exist on type 'PostDoc[]' The issue seems to be related to the fac ...

Reserved space for both double and single quotation marks

I've created a function that generates a table of specified size with predetermined content in each cell, and displays it within a designated div ID. generate_table(4, 4, 'Cell Content', 'display') To test this function, I added a ...

Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child? Link: Check out the stackb ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

What is the most effective method for transferring an error message from the server backend to the vue frontend?

I'm currently working on implementing error handling for a Vue/Vuetify application. The challenge I'm facing involves using external pagination for a datatable that connects to an API with rate limiting restrictions. If users exceed the limit, I ...

Multiple occurrences of setting the state on an array result in logging an empty array each

My current challenge involves fetching data from a backend server and storing it in an array. However, when I attempt to pass this array to another component, I encounter an issue where multiple empty arrays are being passed instead of one filled with data ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...

the term 'this' does not pertain to the user object within the mongoose model

Here is a snippet of my code that saves a user object to a database using Express: api.post('/signup', function (req, res) { var user = new User(); user.name = req.body.name; user.email = req.body.email; user.setPassword(req.body ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

JavaScript: utilizing a function as a hash key

In my program, I need to execute different functions based on the input. If the input matches one of the predefined keys, I want to invoke the corresponding function along with some parameters: var functions = { 'key1': firstFunction, ' ...

Exploring the Power of Viewports and EffectComposer in Three.js

I recently developed an innovative Three.js demo that displays a scene and then adjusts the viewport to show a smaller section of the window with an overhead camera, creating a mini-map effect. You can access the code here: The key portion of the code is: ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

Vue.js powered search bar for exploring countries worldwide (utilizing the restcountries API)

Despite successfully loading the API country data (as evidenced by the console.log() entry and the accompanying picture of my work desk), the country information does not display when hovering the mouse cursor over the search bar field (expecting a dropdow ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

Anticipated reply should have been in the form of an object, however, it

Encountering an issue with resource.get(): "Error in resource configuration. Expected response to contain an object but got an array". Upon configuring the resource to expect an array, a different error arises: "Error in resource configuration. Expected ...

retrieve the source code from all .js links found within the document

There is a file labeled urls.txt. https://website.tld/static/main_01.js https://website.tld/static/main_02.js https://website.tld/static/main_03.js .... All the source code from every .js file in allsource.txt needs to be extracted. Instructions: To ge ...