Send data from input to controller without using $scope

I am encountering an issue with the code below. Typically, I would resolve this problem using $scope, but this time I have been asked to find a solution without utilizing $scope in the controller. I am implementing the "controller as" syntax for managing the view.

<body ng-app="appModule" >
<div ng-controller="calculatorController as calc">

<input type="number" name="firstDigit" placeholder="Enter number" ng-model="calc.firstDigit">

<input type="number" name="secondDigit" placeholder="Enter number" ng-model="calc.secondDigit">

<span>{{calc.result}}</span>

</div>
</body>

(function(){
    angular
        .module("calculatorModule")
        .controller("calculatorController", calculatorController)
            function calculatorController(){
                var calc = this;
                calc.result = calc.firstDigit + calc.secondDigit;
        }
})();

Answer №1

There are two approaches you can take - using watchers or a function to retrieve the result. Personally, I recommend the latter option, but the choice is yours. Here's an illustration of how you can implement it:

Quick tip - familiarize yourself with the controller as syntax as it can help avoid complexities related to nested scopes and parent-child relationship issues with $scope -- Check out this informative article on controller as

(function () {
  angular.module("calculatorModule", [])
    .controller("calculatorController", [function() {
        var calc = this;
        calc.getResult = function() {
          return calc.firstDigit + calc.secondDigit;
        }
        calc.result = calc.getResult();
    }]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="calculatorModule" ng-controller="calculatorController as calc">

  <input type="number" name="firstDigit" placeholder="insert num" ng-model="calc.firstDigit">

  <input type="number" name="secondDigit" placeholder="insert num" ng-model="calc.secondDigit">

  <span>{{calc.getResult()}}</span>

</div>

Answer №2

Your module declaration is incorrect!

It should look like this:

module("calculatorModule", [])

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

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...

Dealing with child elements in isomorphic React applications: a comprehensive guide

Looking at my server code, here is how it appears: var data = { scripts: scripts, children:[<Comp1 />, <Comp2 />, <Comp3 />] }; // keeping smaller for easier example than reality var markup = ''; markup += '<scrip ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

Unable to authenticate through LinkedIn

On my website, I am attempting to retrieve the user's first name, last name, and email using LinkedIn. Here is what I have done so far: In my LinkedIn App settings, under the Default Scope (OAuth User Agreement), I have selected the following options ...

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Duplicating labels with JavaScript

I need assistance with copying HTML to my clipboard. The issue I am encountering is that when I try to copy the button inside the tagHolder, it ends up copying <span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: ...

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...

Detecting changes in parent ref with Vue's v-modelIs this

I am struggling to implement two-way binding because I can't determine if the model ref is being changed by the parent or child component. Using watch captures all changes without any indication of the source of the change. <script setup> // Pa ...

Issue encountered while attempting to pass a function to a child component in React (Uncaught error: TypeError - result is not a function)

How can I pass the result obtained from an API call made in a child component to the parent component? Let's take a look: PARENT COMPONENT: const Parent = () => { function logResult(resultFromAPI) { console.log(resultFromAPI); } ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

To exclude a particular item from an Angular ng-repeat loop within a ul element

On my website, I have a basic dropdown menu that displays a list of available languages. Initially, the page is displayed in the default language, but users can choose another language from the dropdown. The language options are stored in a JSON array, an ...

What is the best way to capitalize the first letter of a string in JavaScript?

Is there a way to capitalize only the first letter of a string if it's a letter, without changing the case of any other letters? For example: "this is a test" → "This is a test" "the Eiffel Tower" → "The Eiffel ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Click-o-Meter: Tracking Button Presses

I’m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...