What is the functionality of this AngularJS application named "HelloWorld"? I have some questions about how Angular incorporates the MVC pattern

Currently, I am diving into the world of AngularJS and taking a course that introduces me to my first AngularJS application. However, I find myself puzzled about its functionality.

This application consists of two main files:

1) index.htm:

<!DOCTYPE html>
<html lang="en-us" ng-app="angularApp">
    <head>
        <title>Introduction to AngularJS</title>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <meta charset="UTF-8">

        <!-- loading bootstrap and fontawesome via CDN -->
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
        <style>
            html, body
            {
                font-size: 1.1em;
            }
        </style>

        <!-- loading angular via CDN -->
        <script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body>

        <header>
            <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/">AngularJS</a>
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
                </ul>
            </div>
            </nav>
        </header>

        <div class="container">

            <!-- This div and its contents are associated with the 'mainController': -->
            <div ng-controller="mainController">

                <h1>Hello world!</h1>

            </div>

        </div>

    </body>
</html>

2) app.js:

/* MODULE: represents a single object in the global namespace.
           Everything inside the element having the custom attribute ng-app="angularApp" is linked to the angularApp variable within the
           global namespace
*/
var angularApp = angular.module('angularApp', []);

// CONTROLLERS
angularApp.controller('mainController', ['$scope', function ($scope) {

}]);

While going through the code, questions arise regarding how it operates.

In my understanding from the app.js file, a module is defined which is essentially a singular object within the global namespace of my application. But what does a module signify in AngularJS? Previously, I have worked with the Spring MVC framework (and some other traditional MVC frameworks) where the module depicts the data displayed in a view.

So what role does it serve in Angular?

From my comprehension, this module is intricately connected to the entire index.htm page because it's declared in the HTML as:

<html lang="en-us" ng-app="angularApp">

Therefore, the statement ng-app="angularApp" on the HTML page suggests that the angularApp module correlates to the events occurring within the index.html page. Is my interpretation accurate or flawed?

Furthermore, within the app.js file, there's also a definition for a controller:

// CONTROLLERS
angularApp.controller('mainController', ['$scope', function ($scope) {

}]);

Is mainController the designated controller name here? It’s established under the angularApp model object.

My perspective on this may seem basic, especially since I'm not well-versed in JavaScript. Here's my understanding:

The mainController variable is an object in JavaScript, and by the preceding line, a controller field named mainController is being added. The logic pertaining to the controller is implemented by the function associated with this new field (as functions can be fields of objects in JavaScript).

Is my explanation correct or lacking some key detail about the controller declaration?

Another point of confusion lies in the use of the '$scope' variable. What purpose does it serve? And what significance does the syntax ['$scope', function ($scope) { ....CONTROLLER LOGIC....}] hold?

This particular controller is linked to a specific view represented by a distinct section of the index.htm page, namely this one:

        <!-- This div and its content is the view associated with the 'mainController': -->
        <div ng-controller="mainController">

            <h1>Hello world!</h1>

        </div>

These details lead to some confusion for me, as they appear quite different from what I've encountered in other Java MVC implementations.

Unlike Java MVC structures, in AngularJS, a view isn't an entire page (like a .jsp page in Java), rather it's a segment of an HTML page bound to a specific controller through the ng-controller="mainController" custom attribute. Isn’t that right?

Additionally, contrary to Java MVC setups, in AngularJS (or in the scenario above), a model isn't just an object containing populated fields for display but is actually an object within the application's global namespace, linked to controllers (acting as fields of the model) responsible for operations on the specified view.

Does my analysis align with the actual workings or am I overlooking key aspects?

Answer №1

Everything seems to be in order, both your controller and view are working properly. Moving forward, the next step would be to create a service to connect to a server API and function as your model.

While the angular 'controller' can function as the model, if you wish to keep only controller/listeners tasks within it, you should create a dedicated service like the one below:

example:

app.service('ContactService', function () {

//'var' acts as private
var contacts = [{
    id: 0,
    name: 'hello world'
}];

//'this' acts as public (which may feel familiar for Java developers)
this.save = function (contact) {
    //connect to the api or work offline here
}

this.get = function (id) {

}

this.delete = function (id) {

}

this.list = function () {
    return contacts;
}
});

your controller

angularApp.controller('mainController', ['$scope','ContactService', function ($scope,ContactService) {
    $scope.contact = ContactService.get(0)
}]);

the view

    <div ng-controller="mainController">

        <h1>{{contact.name}}</h1>

    </div>

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

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

"Trouble with server communication: data array not being passed to hbs

In my GET route, I have the following: app.get(("/employee/:id"), (req, res) => { data.getEmployeeByNum(req.params.id).then((data) => { res.render("employee", {employee: data}); }).catch(function(reason) { res.render("employe ...

How come I am unable to retrieve it as an object (abonnes) using the GetElementById method from the result?

Why am I not able to retrieve 'abonnes' as an object from the result of GetElementById? The element is available in JSON format. function Abonnes() { const [abonnes, setAbonnes] = useState(); const getOneAbonnes = (id) => { Axios.get( ...

What is the best way to distribute javascript and html code across multiple elements on a webpage?

My webpage has a unique feature - two textboxes that trigger a bootstrap modal with a searchable treeview when clicked. The selected item from the treeview automatically populates the textbox. It's a flawless process! Recently, I decided to implement ...

The Backstretch jQuery plugin seems to be malfunctioning

My goal is to achieve a full-screen background image using the Backstretch jQuery plugin on my homepage. Here's the code I've implemented: <div class="startslide"> <script> $.backstretch('IMG_3628.jpg'); </script> < ...

Emphasize certain terms within a text field using Angular 8

I need assistance with selecting specific words from a textarea and generating bootstrap chips. My goal is to highlight the chosen words using various background colors. https://i.sstatic.net/3Rw2z.png export class SearchComponent implements OnInit { c ...

How to implement a jQuery datepicker in Angular with two distinct date formats

I am utilizing a jquery ui datepicker in my angular application, The implementation looks like this: app.directive('dwdatepicker', function() { return { restrict: 'A', require : 'ngModel', link : ...

How can I display a list from an array by clicking a button or calling a function?

After incorporating a button that generates an unordered list from an array (e.g. var list_content = ["Apple", "Banana", "Orange", "Mango", "Papaya"];), each item of the array is displayed as a list item through the li element. The resulting list is append ...

Assign a class to an element depending on its position using JavaScript/jQuery

<ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> How can I use jQuery to add a class to the second li element in the list without using an existing class or id? ...

Altering the content of an item while accessing it from an array

I am facing an issue where I need to update text elements on a webpage based on data retrieved from the server. Even though I can successfully store the references and values, I encounter an error when attempting to access the text value of the object. The ...

Ensure that the setTimeout() function continues to function even after closing and reopening an application

I'm currently working on a Discord.js bot that includes a banning command. The challenge I'm facing is that when I restart the bot, all the setTimeouts get reset. For example, if I ban someone for a week and then restart the bot during that time ...

Leveraging a segment of an established mongoose database

Migrating stats calcul from php to node.js has been a challenging task for me. The previous developer created one collection per client, each with a different schema. However, the calculations I need to perform are consistent across all collections. To ad ...

Identify the ANGLE using JavaScript

I'm experiencing an issue with my WebGL / Three.js game where there is an unhelpful shader program linking error when ANGLE is used for providing WebGL. To address this, I am looking to implement a prominent warning specifically for ANGLE users on the ...

Developing a custom form validation tool using AngularJS in tandem with Django REST on the server

Currently, I am incorporating Angular on the client side to interact with a Django REST Framework backend. To expedite the launch of the project's Alpha version, we opted to utilize server-side validation directly. With Django REST, a JSON string is ...

Implemented text-shadow on a text element utilizing the -webkit-background-clip property

Is there a way to add a drop shadow on text and make the part of the shadow that's inside the text disappear or go behind the background image? .mask { background-image: radial-gradient(purple, gold); background-size: cover; mix-blend-mode: l ...

Cannot close the Bootstrap dropdown after selecting an option

I am encountering an issue with a dropdown list that has a select feature using Bootstrap 3.4.1. The problem is that the dropdown remains open after selection and does not close unless I click outside of the list. Here is the HTML code: <div id="c ...

Objects in Three.js Sparkling from Afar

Currently, I am tackling a project that involves working with scenes containing objects ranging from 10 to 1000000 in size. A recurring issue I have encountered is that when dealing with the larger end of this size spectrum, the objects seem to 'shimm ...

Monitoring the height of an element within an Angular directive

I am attempting to achieve something similar to the following: myindex.html <div ng-controller="MyController" menu> <input ng-model="myVar"/> <div slimscroll="{'height':menuheight,'alwaysVisible':true}"> ...

What sets axios apart from await fetch in Reactjs?

Currently, I am developing a project using Next.js which is built on the ReactJS framework. I am curious to understand the distinction between "axios" and "await fetch". When should we opt for "axios"? As an illustration, here is a snippet of my code: c ...

Trigger a click based on the CSS path starting from a specific element in the DOM

I am currently developing a feature for mouse activities, such as moving the mouse, clicking, and scrolling. I want to be able to record these activities and then playback them later on. So far, I have successfully recorded mouse movement, and now I need t ...