I'm attempting to grasp the concept of AngularJS's controllerAs notation

As I attempted to experiment with controllers by writing up a few examples, I encountered an issue where the controllers would not load. An error message appeared:

firstController is not a function

Upon doing some research, I discovered that Angular 1.3.x no longer supports global controllers. The new method of creating controllers involves defining them in the app.js file instead. This led me to question whether I now have to create all my controllers in this centralized file as opposed to having separate files for each controller. I tried adjusting the controller creation like so, but still faced challenges:

UPDATE: I modified my controller based on jedanput's suggestion, switching $scope to this.

app.controller('firstController', [function(){
 this.name = "Tim";

}]);

I also found it frustrating that most examples out there still refer to the old approach used in Angular 1.2. Any assistance in understanding this issue would be highly appreciated.

EDIT: Here is the content of my index.html file. Hopefully, this will provide more context to help identify the problem.

<!DOCTYPE html>
<html lang="en"  xmlns:ng="http://angularjs.org" id="ng-app"       ng-app="myApp">

<head >
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>ControllerAs</title>
    <meta name="description" content="">

</head>
<body>

<div class="content" ng-view=""></div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular-route.js"></script>

<script type="text/javascript" src="../js/app.js"></script>

<script type="text/javascript" src="../js/directives/it-works.js">    </script>

<script type="text/javascript" src="../js/controllers/firstController.js"></script>
<script type="text/javascript" src="../js/controllers/secondController.js"></script>

</body>
</html>

Although I've managed to work without using Controllers thus far by relying on directives and services, I feel it's time to delve deeper into controllers. It seems like there might be a fundamental concept that eludes me. Once again, any guidance would be greatly valued.

UPDATE: despite making adjustments, the error persists. Sharing my app.js file below, hoping it may offer some insight into the issue.

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

app.config(function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: "../partials/test-skeleton.html"
    })
});

Answer №1

Here is the correct way to implement it:

app.controller('firstController', ['$scope', function($scope){
     $scope.name = "Tim";
}]);

Additionally, using the controllerAs syntax simplifies the code by avoiding the use of 'this':

<div ng-controller="oneCtrl">
    {{name}}
</div>

Instead, you should use:

<div ng-controller="oneCtrl as one">
    {{one.name}}
</div>

This approach is especially helpful when dealing with nested controllers.

Answer №2

It is true that Angular offers various notations, which can be frustrating and perplexing. To avoid confusion, I suggest following the guidelines outlined in John Papas Angular Style Guide. He advocates for the following structure:

(function() {
     'use strict';

      // Referencing your application
      angular.module('myapp')
          // Defining the controller
          .controller('mycontroller', controller);

      // Explicitly injecting the controller arguments 
      controller.$inject = ['$scope', '$http'];

      // Defining the actual controller function with injected arguments
      function controller($scope, $http) {
            // Controller logic
      });
})();

Maintaining a clean global space is crucial. This is why enclosing everything within an Immediately-Invoked Function Expression (IIFE) is emphasized. It's also important to clearly define injection dependencies using the $inject array to ensure proper minification in the future.

I understand this introduces another method of defining AngularJS components. John Papa's style guide is well-known and widely recognized. Collaborating closely with the Angular team ensures alignment with new versions, making transitions smoother.

Contrary to popular belief, everything doesn't have to be in one file. Simply ensure that the file containing angular.module('myapp',[]) is loaded before others. This declares the myapp module and appends controllers accordingly.

Upon reflection, there is another approach: creating a new module in the same file, attaching the controller, and then loading that module into your application. Complexity may arise, but exploring different methods can enhance understanding.

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 to extract selected value from a dropdown menu in a React component

Is there a way for me to retrieve the chosen value from the dropdown menu? The select dropdown contains 12 options. My goal is to capture the selected value and then utilize it in handlecolumnchange to manipulate the number of columns added or removed. Des ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

Determine the fill color attribute value of a rectangle using Testcafe paired with typescript

Here is a code snippet I need help with: <colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www. ...

Top strategy for monitoring a user's advancement in reading different text segments

If you are familiar with zyBooks, I am looking to implement a similar feature where users can track the sections they have read and mark them as completed with a button. However, I am struggling conceptually with determining how best to structure my mongo ...

How can one retrieve the x and y coordinates from the client's browser and pass them to the server in a Bokeh server setup?

I'm currently working on a Bokeh server app called getcoords.py. To start the server, I use the command: bokeh serve getcoords.py. The app includes a HoverTool with a CustomJS callback function and a quad glyph configured to trigger a selected event o ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...

Navigating through various JavaScript libraries with varying loading times can be a tricky task when working within the Angular

As I dive into learning Angular, I find myself pondering the architecture of my app. The project I'm embarking on will heavily rely on various external libraries such as jQuery, jQuery.ui, jsPlumb, and more, each with their own loading times. I unde ...

The @angular/http package version 4.3.5 is not meeting the peerDependencies requirements of its sibling packages!

Currently in the process of setting up my own open source application, which can be found on this link. Encountered an error message when trying to execute tns run android --emulator: Unable to install dependencies. Ensure that your package.json ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Is there a way to convert an array into an object where the first value in the array becomes the name and the properties are an array of the remaining values within subarrays?

Looking to efficiently group elements of a multidimensional array with an unknown list, and transform it into an object while removing duplicate values in the first element of each subarray: For instance, here's the initial array: const arr = [[a, 1 ...

Navigating nested loops within multidimensional arrays

Currently, I am experimenting with nested loops to search through nested arrays in order to find a specific value called "codItem". Below is a test model for the array (as I do not have access to the original fetch request on weekends): let teste = [{ it ...

Use the npm-search feature to show only the name and description columns in the search results

After running the command npm search packagename, I noticed that the results are shown in 6 columns: name, description, author, date, version, and keywords. Is there a way to customize npm-search so that it only displays the name and description columns? ...

transferring various data from JavaScript page to PHP page

Is it possible to pass multiple values from a service page to a PHP page? I am trying to pass the values 'data', 'albimg' and 'albvideo' to the PHP page, but I keep encountering an error. Please refer to the image below for mo ...

"Encountering a net::ERR_UNKNOWN_URL_SCHEME error message when making an Ajax post request

I'm encountering an issue while attempting to make a post call using Ajax from my frontend to my Express server. The error message I'm getting is net::ERR_UNKNOWN_URL_SCHEME. Here's the code snippet for the Ajax request: function sendStep ...

The HTML is not rendering as planned

I have 2 files, test.html <!DOCTYPE html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./test/jquery.min.js"></script> </head> <body> ...