The data being retrieved from the controller in AngularJS is not displaying as expected

Just started learning AngularJS.

Currently following this MEAN Stack Intro: Build an end-to-end application

Created a basic html file to test .

index.html

<html>

    <head>
        <meta charset="utf-8">
        <title>Stack POC</title>
        <script type="application/javascript" src="app/scripts/controllers/user_controller.js"></script> 
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    </head>
    <body ng-app="userListApp">
        <div ng-controller="userListController">
            <h1>Total users: {{userCounts}}</h1>
        </div>
    </body>
</html>

app/scripts/controllers/user_controller.js

angular.module('userListApp', []).controller('userListController', function($scope){ 
                $scope.userCounts = 10;
                });

However, upon running the code, I don't see:

Total users: {{ userCounts }}

Instead of displaying the count as 10.

Using and for development server setup.

gulpfile.js

var gulp = require('gulp'),
    connect = require('gulp-connect');

gulp.task('serve', function() {
    connect.server({
        root: '.',
        port: 8888
    }); 
}); 

gulp.task('default', ['serve']);

package.json

{
  "name": "poc",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-connect": "^3.2.2"
  }
}

Viewing the page on 45.0.2 browser.

Answer №1

The reason you're encountering an issue is because you're only providing a single function and not a complete controller.

You can try something similar to the following code:

<html>
    <head>
        <meta charset="utf-8">
        <title>Stack POC</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> 
        <script>
        angular.module('userListApp', []).controller('userListController', function($scope){
            $scope.userCounts = 10;
        });
        </script>
    </head>
    <body ng-app="userListApp">
        <div ng-controller="userListController">
            <h1>Number of users: {{ userCounts }}</h1>
        </div>
    </body>
</html>

In this example, you need to create a module (here named userListApp) using the angular.module() function. The second parameter should be an array of dependencies (empty if there are none). Within this module, you can define a controller. Remember to include $scope as a parameter in the controller function so that it can be used within your code. Inside the controller, you can assign values to variables, just like in your previous attempt.

Answer №2

Make sure to include the AngularJS app instantiation in your script. Remember to pass the application name as an argument to ng-app in the body tag and update the script accordingly.

Don't forget to link the function userListController to the AngularJS controller using app.controller.

For a reference, check out this working fiddle:

https://jsfiddle.net/akonchady/7kfv4ssk/1/

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

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...

Input form and select form collide in conflict when the "Enter" key is activated

My search box includes input forms and a select form with various options. The issue arises when using the place autocomplete feature from Google Maps alongside the select form. When the enter key is pressed after entering a location in the autocomplete fi ...

Having trouble with table sorting in Jquery?

I am a beginner in the realm of Jquery and web programming. Recently, I attempted to implement the tablesorter jquery plugin for one of my projects but encountered issues with making it work properly. In search of a solution, I turned to Stack Overflow. C ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

Adjust the visibility of components depending on the width of the screen

In my project, I have a Wrapper component that houses filters. This component becomes visible when the openMobileFilters() function is called and disappears when closeMobileFilters() is triggered. The Wrapper component occupies the entire page, and I want ...

Selecting a directive's scope

Though the title may not capture it quite accurately, I struggled to find a more fitting description. I crafted a directive that incorporates an ng-repeat: app.directive('appDirective', function($purr){ var template = '' + ...

Error encountered: iPad3 running on iOS7 has exceeded the localStorage quota, leading to a

Experiencing a puzzling issue that even Google can't seem to solve. I keep getting the QuotaExceededError: DOM Exception 22 on my iPad3 running iOS7.0.4 with Safari 9537.53 (version 7, WebKit 537.51.1). Despite turning off private browsing and trying ...

Middleware in Express not producing results

Here is the code I am currently using: var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.cookieParser()); var port = Number(process.env.PORT || 5000); app.get('/test/:id', function(r ...

Exploring the world of Next.js version 9.3 and beyond with the exciting addition

As a beginner with Next.js, I am seeking guidance on utilizing getStaticPaths and getStaticProps within catch-all routes. Many blog starters for Next.js 9.3+ focus on single-level blog posts (such as /posts/post-1.md, /posts/post-2.md, etc.), but I am stru ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

Can VueJS support multiple v-slots in a component?

I recently set up vee-validate v3.0 for validation in my project and everything was going smoothly until I tried to style my elements. Despite following the documentation on styling and making changes to the vee-validate config, I encountered a new issue - ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Creating a zebra-striped list using CSS can be done by styling even and odd list items differently

I am facing an issue with Angularjs and the table tag when using group loops. The problem arises in achieving correct zebra striping for the list. How can I solve this to ensure the zebra pattern is applied correctly? <table> <tbody> <tr ...

Having trouble with JQuery Ajax when trying to send multiple data at once?

name = "John Doe"; username = "johndoe123"; password = "secure123"; $.ajax({ type: 'POST', url: "https://example.com/api", data: { name: name, username: username, password: password }, success: function(response, status, xhr ...

Navigating directly to a page in ReactJS and Redux without needing to login if a token is found in the local storage

Currently in the main component, it is set to automatically redirect to the Login page. However, I want to implement a check to see if a token is already stored in the local storage. If a token exists, I want the application to skip the Login page and dire ...

Insert a Facebook like button within a designated div

Can anyone figure out why the Facebook button isn't functioning properly? ---- ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

dynamic variable to store user input (Meteor)

I'm still trying to grasp the concept of reactive programming in Meteor, so I have a question that may seem silly: Instead of "injecting" data using the template system as documented, can I use it to extract data? For example, if I have a textarea li ...