Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html>
    <html ng-app="myApp" >
        <head>
            <title>myApp.html</title>
        </head>

    <body ng-controller="myCtrl as vm">

    <br><br>
    <div>

       <p> Inserisci un colore <input style="background-color:{{colore}}" ng-model="colore" value="{{colore}}"> </p>
        <body bgcolor="{{colore}}">
    </div>

    <div > 

       <p>Nome: <input style="background-color:{{colore}}" type="text" id="nome" onkeyup="" ng-model="vm.utente.nome"></p> 
       <p>Cognome: <input style="background-color:{{colore}}" type="text" id="cognome" ng-model="vm.utente.cognome"></p>

       <p id="prova" value="test">{{myFunction}}</p>
       <p>{{vm.saluta() | uppercase}}</p>

    </div>



       <p id="demo">prova</p>

        <button onclick= vm.myFunction()> Prova</button>

            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
            <script type="text/javascript" src="C:\Users\user1\Desktop\myCtrl.js"></script>
</body>
</html>

myCtrl.js

(function() {
    'use strict';
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function() {
        var vm=this;
        vm.utente = {nome: "Mario", cognome: "Rossi"}; 

        vm.saluta = function() {
            return "Buongiorno " +
                this.utente.nome + " " +
                this.utente.cognome + "!"

        };

        vm.myFunction = function() {
        var text = document.getElementById("demo").innerHTML;
        document.getElementById("demo").innerHTML = text.toUpperCase();
        };

        function test2() {
         console.log("Hello!");
        };
    });
})();

i'm struggling with understanding AngularJS and trying to solve errors in my code. I've seen examples where everything is in a single HTML file with script tags, but I prefer separating the controller into a separate file. In my approach, I am connecting the controller without using $scope, simply replacing "this" with vm (var vm = this). I just want to run some basic tests with functions, but always encounter this error:

myApp.html: 30 Uncaught ReferenceError: vm is not defined at HTMLButtonElement.onclick (myApp.html: 30)

The first function works fine, I get the output from "vm.saluto()" only if I call it using the format: {{vm.saluto}}. Why doesn't onclick and others work?

Can anyone provide assistance? Where am I making a mistake?

I have looked at similar cases and discussions, but haven't been able to find a solution yet.

Answer №1

Your example seems to be working fine.

Just a heads up, you have two body tags in your code.

It's important to note that the name vm defined in the controller as is not the same as the local variable vm within your controller's function.

Also, it's recommended to avoid direct DOM manipulations when working with AngularJS.

Please refer to the example below:

(function() {
    'use strict';
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function() {
      var vm = this;
      vm.utente = {
        nome: "Mario",
        cognome: "Rossi"
      };

      vm.saluta = function() {
        return "Buongiorno " +
          this.utente.nome + " " +
          this.utente.cognome + "!"
      };
      
      vm.test = 'prova';
      vm.myFunction = function() {
        vm.test = vm.test.toUpperCase();
      };

      function test2() {
        console.log("Hello!");
      };
    });
  })();
  
<html ng-app="myApp">
  
  <body ng-controller="myCtrl as vm">
    <p>{{vm.utente.nome}}</p>
    <p>{{vm.saluta()}}</p>
    <button type="button" ng-click="vm.myFunction()">test</button>
    <p id="demo">{{ vm.test }}</p>
  </body>
  
  </html>
  
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

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

What is the best way to send these values to a JavaScript function and show them one by one on an HTML webpage?

There are 100 values stored in the database. https://i.stack.imgur.com/584Op.jpg I need to retrieve these values from the database using PHP and pass them to JavaScript using Ajax. PHP CODE: for($i=0;$i<=9;$i++) { $random = (10 * $i) + rand(1,10); ...

Upon exchanging data with the router located in the navigation bar, a continuous loop occurs as I initiate the download operation involving the electron-dl and electron-download-manager tools

When I switch to the router in the navbar, a loop occurs when I try to initiate the download process. I've been struggling with this issue for the past 2 days and can't seem to find a solution. function downloaddosya1() { console.log("Fi ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

The JQuery video player's full screen toggle feature is not correctly assigning the class name

I've been tackling a bug in my JavaScript/jQuery video player that has left me stumped. One of the key features of this player is an enter/exit full-screen button located at the bottom of the HTML snippet: (function($) { /* Helper functions */ ...

Leveraging JSON Data for Dynamic Web Content Display

I have been attempting to parse and display the JSON data that is returned from a REST API without any success. When tested locally, the API's URL structure is as follows: http://localhost/apiurl/get-data.php It returns data in the following format ...

What is the purpose of using CORS with Express?

Here is how my express server setup looks: const cors = require('cors'); const express = require('express'); const app = express(); const port = 8000; app.use(cors({origin: 'http://localhost:8000'})); // Handle requests of c ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

Parent window login portal

I have just started learning how to program web applications, so I am not familiar with all the technical terms yet. I want to create a login window that behaves like this: When a user clicks on the Login button, a window should pop up on the same page t ...

Using JavaScript in Node, you can pass an object by throwing a new Error

How can I properly throw an error in my node application and access the properties of the error object? Here is my current code: throw new Error({ status: 400, error: 'Email already exists' }); However, when I do this, I get the following outpu ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

Uploading files and data in Laravel using Vue.js and Vuetify: A step-by-step guide

My Vuetify form is working fine with text input, but when I try to include images, I encounter the error GET http://danza.test/thumbnails[object%20File] 404 (Not Found). How can I successfully pass both text and images in a form? This is part of the code ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

A guide to parsing JSON files and extracting information

How can I extract the name and status from a JSON object? I've attempted various methods like [0] - [1], as well as trying without, but to no avail. [ { "status": "OK" }, { "id": "1" ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

When attempting to pass data to a modal, an error occurs due to props being undefined. This results in a TypeError with the message "Cannot

I'm working on a product listing feature where each item displays some information along with a "more details" button. When the button is clicked, a modal window opens to show additional details of the specific product (using props to pass data betwee ...