Distinguishing between creating controllers in AngularJS

I am a beginner in the world of AngularJS and I have come across two different examples when it comes to creating a controller. However, the one that is more commonly used doesn't seem to be working for me.

The problem with the first example is that it either cannot locate the module or the function, resulting in displaying just {{type}} {{name}} on the screen. Interestingly, when I try it on Plunker, the first example works fine.

'dataControl' is not a function, got undefined

This is the error message I am encountering.

If my HTML looks like this:

<html ng-app>
<head>

</head>


<body ng-app="docsBindExample">

<script src="../bower_components/angular/angular.min.js"></script>
<script src="../scripts/controllers/main.js"></script>


<div ng-controller="dataControl">

    <select id="selected" ng-model="type">
        <option>Total Revenue</option>
        <option>Total Expenditure</option>
        <option>Total Number of Events</option>
        <option>Amount of Mail</option>
        <option>Average Delivery Times</option>
        <option>Critical Routes</option>

    </select>

    {{type}}
    {{data}}

    <ul>
        <li ng-repeat="values in data">
            {{values.dataName}}
            {{values.dataValue}}
        </li>
    </ul>

</div>
</body>
</html>

And then there's the first controller that isn't functioning as expected:

angular.module('docsBindExample', [])
    .controller('dataControl', ['$scope', function($scope) {


        $scope.name = 'Value Is here';
    }]);

On the other hand, there's the second controller which seems to work smoothly:

function dataControl ($scope) {


    $scope.name = 'Value Is here';
}

Are there any drawbacks to using the second approach?

Answer №1

When it comes to the second approach, there are no apparent drawbacks. However, the first approach proves to be more convenient for larger applications as you can define modules and register controllers and filters within them. If your first approach is not working, it could be because you have not defined the docsBindExample module. To resolve this issue, try the following:

var docsBindExample = angular.module('docsBindExample', []);

After defining the module, proceed with your controller definition.

Answer №2

Check out the code snippet below:

View Demo

HTML

<div ng-app="docsBindExample">
<div ng-controller="dataControl">

    <select id="selected" ng-model="type">
        <option>Total Revenue</option>
        <option>Total Expenditure</option>
        <option>Total Number of Events</option>
        <option>Amount of Mail</option>
        <option>Average Delivery Times</option>
        <option>Critical Routes</option>

    </select>

    {{type}}
    {{data}}

    <ul>
        <li ng-repeat="values in data">
            {{values.dataName}}
            {{values.dataValue}}
        </li>
    </ul>
</div>
</div>

JavaScript

var app = angular.module('docsBindExample', []);
app.controller('dataControl', function ($scope) {
   $scope.name = 'Value Is here';
});

Answer №3

From a syntactical standpoint, both methods function correctly; however, the first approach is preferable to the second. In the first method, the controller is attached to the module, which is considered best practice when developing an application.
For further information, you can visit the following link:
https://docs.angularjs.org/guide/controller

I did not encounter any errors when running your code.

Answer №4

I'm thrilled to say that your code is functioning perfectly for me!

If you'd like to see it in action, check out this link: http://plnkr.co/edit/hrkSDOinTcMEmPLcttut

You might also find these links from Stackoveflow helpful:

AngularJS - different ways to create controllers and services, why?

Globally defined AngularJS controllers and encapsulation

Answer №5

The preferred method is the first one, mainly because it prevents polluting the global object.
Although I have not personally tested it, it is likely that you will encounter difficulties as your application grows in complexity (involving multiple modules and external dependencies).

The error you are experiencing is probably a result of a JavaScript error (such as a syntax mistake) causing the dataControl to not register properly as a controller.

Unfortunately, these errors can be vague and challenging to pinpoint.
I recommend commenting out all the code within the controller definition, then gradually uncommenting blocks until you identify the problematic line.


In my experience, many such errors were caused by incorrect object declarations:
For instance, using {prop = val} instead of {prop: val}, or {p1:v1; p2:v2} instead of {p1:v1, p2:v2}.

Answer №6

consider updating it to this:

.controller('infoCtrl', function($scope) {
   //additional code
 });

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

Maintain the active menu open when navigating to a different page on the website

My website has a dropdown menu, but whenever I click on a submenu link, the new page opens and the menu closes. However, I want the active menu to remain open on the new page of the website! To demonstrate what I have tried in a simple way, I created an e ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Unexpected failure when using FormData in Ajax callback for large files

I have a file upload control where I can upload various types of files. After getting the file, I store it in a FormData object and make an ajax call to my controller. Everything works well with images and small .mp3 files. However, when I try to upload .m ...

What is the best way to retrieve the offsetHeight of a Component Element using Vue.js?

I am currently working on a Vue.js component and successfully inserting it into the DOM. My goal is to find out its rendered height once it's in the DOM, specifically its offsetHeight. However, I seem to be missing something obvious as I can't fi ...

Utilizing jQuery to generate dynamic nested divs within the ul li tags

I am looking to dynamically generate nested divs within a ul li. The goal is to create the following structure programmatically: <ul> <li> <div class="videoThumbnail"> <img src="./img6.jpg" /> &l ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Guide to transferring array information from one Vuejs route to another

I'm facing an issue with passing an array from one Vuejs route to another. Specifically, I need to pass the array from home.vue to post.vue. In my route.js file for post.vue, I have: { path: '/post/:cart', name: 'post', com ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

Is the NPM package not being imported? How exactly is it being utilized?

mediacms-vjs-plugin is a unique plugin designed for Video.js. The MediaCmsVjsPlugin.js source code begins with: import { version as VERSION } from '../package.json'; import 'mediacms-vjs-plugin-font-icons/dist/mediacms-vjs-icons.css'; ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

Is it possible to inject $http into an Angular Service and then transfer that data to a controller?

I need assistance with loading JSON data from an external file in AngularJS using a service. myApp.service('ContactsListService', function($http) { var contactsList = $http.get('js/contacts.json').success(function(data){ return ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

prepend a string to the start of ng-model

I am looking to enhance my ng-model variable by adding a specific string to it. This ng-model is being used for filtering data, specifically for elements that begin with the term "template". By adding this string to the ng-model, I hope to improve my searc ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

Recursively apply a custom condition to filter a tree

Within this tree structure, I need to extract items with a release version of 0.0.1 to use in building my navigation based on that specific release number. { title: '', items: [ { title: '', path: '', ...

Using the .load() function to import an HTML file from the directory above

I am trying to achieve the following structure: folder1 index folder2 page to load Can I dynamically load the 'page to load' in a div within the 'index' page using DIV.load()? I have attempted various paths (../folder2/page, ./, ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

What are the benefits of integrating firebase-admin-sdk with firebase-ui and firebase-client-sdk for both server-side and client-side authentication management?

I am currently working on implementing an authentication mechanism for my Next.js project. Specifically, I plan to utilize firebase-auth and firestore. My main goal is to keep important security logic on the server side to ensure safety. I want to avoid ex ...