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

Implementing a smooth transition for a never-ending CSS rotation animation upon clicking a different div with the help of jQuery

I am attempting to utilize jquery in order to bring a constantly rotating div (with CSS animation) to a gradual, smooth halt when another div is clicked. My current strategy involves changing the "animation-timing-function" property from "linear" to "ease ...

What could be causing my POST route to be missing in my MERN stack application?

I'm encountering two issues with a MERN stack application: i) Despite the POST route working, Axios fails to send form body data to the server. MongoDB only displays default field values after each submission. ii) The POST route was operational init ...

Simplifying complex JSON structures by un-nesting arrays

Within my Formik form, I have 3 fields: MemberMemberID, EventEventID, and event_date. This form represents an event (such as a Tuesday club) taking place on a specific date and attended by various members. Formik stores the data in key-value pairs within ...

What is the reason behind the absence of compile time errors when using 'string' functions on an 'any' field type variable in TypeScript?

Looking at the following typescript code snippet: let a; a = "number"; let t = a.endsWith('r'); console.log(t); It is worth noting that since variable 'a' is not declared with a specific type, the compiler infers it as ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Guide to utilizing the importcss plugin in TinyMCE Version 4.0.10: Troubleshooting content_css loading issue and resolving style dropdown display problem

We are currently using the latest version of TinyMCE, specifically v 4.0.10 Our goal is to load content_css and have a dropdown of styles available in the styleselect menu. According to TinyMCE 4.x documentation, we attempted to achieve this by incorpora ...

NodeJS - issues with nodemon auto-reload feature causing my server to not

After successfully installing NodeJS version 4.4.5, I proceeded to install nodemon version 1.9.2 by following all the installation instructions using npm (npm install -g nodemon). In a newly created folder, I have my server.js file with some basic code: ...

Omit the <span> tag when exporting to XLS format

Currently, I have a functioning jQuery DataTable that utilizes the TableTools plug-in and includes <span> elements in one of the columns for each row. When clicking on the export button, my goal is to exclude or hide the <span> elements from t ...

Troubleshooting: MongoDB/mongoose post save hook does not execute

My current setup involves the following model/schema: const InvitationSchema = new Schema({ inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Orga ...

How to Display Bootstrap4 Modal in VueJS without using Jquery

Is there a way to display a Bootstrap modal from a function in VueJS using vanilla JS? I am working on a project that only uses standard Bootstrap 4 and not BootstrapVue. //component.vue <template> <div> <button type="button" class ...

What purpose does the next() function serve in Express.js?

Using this script to kickstart my next js app. I can't share the entire script, but I do need some assistance with the following: What is the purpose of compression? What is the importance of using helmet? What does next({dev}) do? const express = re ...

React.js - Implementing a Delayed Loading Indicator to Prevent Flickering

How do I implement a loading indicator in React that only appears if the loading state is true for over 1 second, and if it resolves before 2 seconds, show the indicator for at least 1 second? In Angular JS, there was a similar question with 5 conditions: ...

Modifications made in one controller do not reflect in the second controller

One issue I'm facing is with a drop-down list that I have. <md-option ng-repeat="person in people" ng-value="person"> {{ profile.lastname }} </md-option> Whenever I change the value, saving works fine and refreshes the drop-down list ...

Testing the capabilities of AngularJS with e2e testing using the angular-recaptcha library

I have been attempting to e2e test my basic application, but I am facing challenges with the angular-recaptcha plugin from VividCortex (https://github.com/VividCortex/angular-recaptcha). Here is the test case I am working on: it('should redirect t ...

Acquiring the item by referencing one of its property's values

Imagine you have a JSON structure that looks like this: [ { "name":"Foo" "nickname":"Lorem Ipsum" }, { "name":"Bar" "nickname":"Dolor S ...

What is the best way to activate a JQ function with my submit button?

Is there a way to trigger a JQ function when clicking the submit button in a form? I managed to make Dreamweaver initiate an entire JS file, but not a particular function. ...

Iterating over objects within a nested array using ng-repeat

My back-end is sending me an array of string arrays (Java - CXF-RS). The length of each array within the string arrays ranges from 1 to n. In order to display this data on my front-end, I am utilizing ng-repeat. Everything is functioning correctly with o ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...