Troubleshooting: Why is my AngularJS Controller not functioning properly

I attempted to run a basic Angular example utilizing a controller, but it does not appear to be functioning correctly.

Below is the HTML code:

    <!DOCTYPE html>
    <html ng-app = "app">
    <head>
        <title></title>
        <script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/my.js"/> 
    </head>
    <body>
    <label for = "fname">Name:</label><input type="text" id="fname" ng-model="name"/>{{name}}
    <div class="container" ng-controller="SimpleController">
        <ul>
            <li ng-repeat="hero in heroes">{{hero.name}} - {{hero.city}}</li>
        </ul>
    </div>
    </body>
    </html>

The content of my.js is as follows:

angular.module("app",[]).controller('SimpleController',[function ($scope){
    $scope.heroes = 
    [
        {name:"Bruce Wayne", city:"Gotham"},
        {name:"Kal-El", city:"Metropolis"},
        {name:"Barry Allen", city:"Central City"},
        {name:"Kara Jor-El", city:"National City"},
        {name:"Shazam", cuty:"Fawcett City"}
    ];

}]);

While the ng-model directive works on my local system, the controller does not. I am currently using AngularJS 1.4.x (stable).

I have tried following other suggestions from previous questions, but still no luck. Can someone point out what I might be doing incorrectly?

I also created a JSFiddle demo. However, even within the JSFiddle environment, the ng-model does not seem to be functional.

Answer №1

Make sure to inject $scope properly into your controller by including it in the array like this:

angular.module("app",[]).controller('SimpleController',['$scope', function ($scope){
// Your code here
}]);

SPECIAL NOTE

Although it is acceptable to pass the controller function as the second argument, using this method (passing an array with dependencies and controller function) is recommended if you plan to minify your code for production.

Minifiers often change variable names during minification which can cause issues with dependencies, but this method ensures that everything will still work correctly even after minification.

Answer №2

For those utilizing a more contemporary version of AngularJS, my recommendation would be to opt for the ControllerAs syntax:

<div class="container" ng-controller="SimpleController as simpleController">
    <ul>
        <li ng-repeat="hero in simpleController.heroes">{{hero.name}} - {{hero.city}}</li>
    </ul>
</div>

Furthermore, in the JavaScript section:

angular.module("app",[]).controller('SimpleController',function (){
    this.heroes = [
        {name:"Bruce Wayne", city:"Gotham"},
        {name:"Kal-El", city:"Metropolis"},
        {name:"Barry Allen", city:"Central City"},
        {name:"Kara Jor-El", city:"National City"},
        {name:"Shazam", cuty:"Fawcett City"}
     ];

  }]);

Answer №3

Here is an example of how your controller could look:

 angular.module("app",[]).controller('ExampleController',function ($scope){
    $scope.superheroes =  [
      {name:"Peter Parker", city:"New York"},
      {name:"Bruce Banner", city:"New Mexico"},
      {name:"Tony Stark", city:"Malibu"},
      {name:"Diana Prince", city:"Themyscira"},
      {name:"Arthur Curry", city:"Atlantis"}
    ];
});

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

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

What is the best way to include React globally when running unit tests?

In my Rails project, I have integrated the react-rails gem, which sets up a global variable like this: window.React = React; While this is convenient for regular usage, it causes issues when running unit tests with Jest because the global React variable ...

When the getImageData event is triggered upon loading

Hello, I have a script that identifies transparent and non-transparent pixels. Currently, the result is displayed from a 100px by 100px rectangle on mouseover: var data = ctx.getImageData(100,100, canvas.width, canvas.height).data; During mouseover, it s ...

What is the process for extracting an array from an object?

How can I retrieve an object from an array using Node.js? I have tried the code below, but it's returning the entire object. What I actually need is to only print the name, for example, just "sethu". Code: var sethu = [{ name:'sethu', ...

Implementing TestCafe with a Rails backend and utilizing fixtures data for testing

Currently, I am involved in a Rails project that utilizes RSpec for testing. We rely on various Rails fixture data to test our UI under different conditions. Recently, I came across TestCafe for handling functional UI testing, and I find it quite intrigui ...

Restrict the duplication of div elements with JQuery

Here is the structure I'm working with: <div class="checkmark-outer"> <div class="checkmark-33"> <div class="fa-stack fa-1x checkmark-icon"> <i class="fa fa-circle fa-stack-2x icon-background"></i> ...

"Jquery with 3 buttons for toggling on and off individually, as well

There are 3 buttons available: button 1, button 2, and button 3. Button 1 toggles the show/hide functionality of the left side, button 2 does the same for the right side, and button 3 affects both sides simultaneously. What is the best approach to achieve ...

Adding elements to an array using JavaScript

What is the correct way to add new values to an array like this? json = {"awesome":"45.22","supercool":"9876"} I attempted json.push("amazingness":"45.22");, but unfortunately it was not successful. ...

Use jQuery to assign a value of "true" when a checkbox is

Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...

Inserting information into an array: Access the final index consistently with TypeScript

I am interested in dynamically creating a table by allocating it, with the variable nbrBoules: boules:Boule :[] boule:Boule; Boule{id,poids} Method(){ for (var _i = 0; _i < this.nbrBoules; _i++) { this.boule.id = _i; alert(_i); this ...

Encountering a 404 error while attempting to establish a connection between Express and React

My attempt to make a simple API request for bitcoin values is encountering some issues. When I enter in my Chrome browser, I receive a "Cannot Get /" message with a 404 error in the dev tools stating "GET 404 (Not Found)". However, when I visit , I succ ...

Clicking the button becomes impossible after entering text and using `evaluateJavascript`

I am currently working on finding a solution to input the receipt number and click the 'Check Status' button on this specific website: After successfully entering the receipt number: document.getElementById('receipt_number').value = &a ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

Sharing filtered data between controllers in AngularJS is a powerful feature to enhance data

One common topic of discussion is how to share data between controllers. In my case, I addressed this issue by creating a factory that contains functions for calling our API and retrieving the data we need. angular.factory('polygonService', [&ap ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

Utilize Node.js to simultaneously connect with several APIs

Consider a scenario where multiple APIs need to be called in parallel using promise.all(). The issue arises when promise.all() rejects if any API fails. In this case, instead of giving up on failed APIs, I want to retry them until they succeed. However, ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

Exploring the Wonders of React Memo

I recently started delving into the world of React. One interesting observation I've made is that when interacting with componentized buttons, clicking on one button triggers a re-render of all button components, as well as the parent component. impo ...

What is the process for handling authorization in RESTful requests using angularjs?

Currently, I am utilizing angularjs to send REST requests to an API that necessitates authorization. The authorization process demands the request to be signed (reminiscent of how Amazon s3 operates), and this signature must be included in the headers. My ...