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

Having trouble with the dropdown multiselect feature in AngularJS?

I'm striving to develop a straightforward multi-select dropdown utilizing angular JS, bootstrap, and JS. This dropdown should display days (mon, tue...sun), with options for select all and unselect all. My goal is to create a controller that will de- ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Leverage the power of express-session in your NextJS project

Currently, I am working on developing a login system using NextJS and MySQL. I am looking to implement sessions for user login, but I am unsure of how to integrate express-session with NextJS. Can anyone provide guidance on whether express-session can be ...

Buefy table in Vue with various row statuses

One interesting feature of Buefy tables is the ability to highlight rows with a specific color based on a variable in the row. :row-class="(row, index) => row.variable === x && 'is-info'"> In order to style the specific row class: <styl ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

Troubleshooting issues with the sidebar navigation in Laravel project using Vue and AdminLTE

I successfully installed AminLte v3 via npm in my Laravel + vue project and everything is functioning properly. However, I am facing an issue when I attempt to click on the main menu item in the Side navbar that is labeled as <li class="nav-item has-tr ...

Make sure to display at least one view separate from the ng-view in Angular

I am trying to configure my app to always display the template of the CategoryController on every page. The app currently showcases all categories with this controller: when a category is clicked, it displays all books in that category, and navigating thro ...

Tips for referencing a function declared within a prototype

I have been attempting to enhance a web page by adding functionality using a jquery library that lacks documentation. The problem I am encountering is primarily due to my lack of understanding of the jquery plugin model and/or the inner workings of javascr ...

"Troubleshooting the issue of Delete Requests failing to persist in Node.js

Whenever I send a delete request to my node.js server, it can only delete one item from my JSON file until the server restarts. If I attempt to make a second delete request, it successfully deletes the item but also reverts the deletion of the last item. ...

Exploring Google with Angular.js

When designing my website, I incorporated Angular in a specific section rather than the entire site. However, I have learned that Google encounters difficulties when indexing Angular content. To ensure optimum visibility for both search engines and users ...

Discover the array of results by implementing a while loop in JavaScript

My goal is to create a list of outputs that are not evenly divisible by numbers smaller than the input value. For example, if the input value is 10, the list should be 10, 9, 8, 7, 6, 4, 3, 1. I have written some code in JavaScript for this purpose, but ...

Interactive JS chart for visually representing values within a preset range in Vue.js

I was in need of a custom JavaScript chart specifically designed to display a value within a specified upper and lower limit. The main application for this would be illustrating the current stock price between its 52-week high and low ranges. It was essent ...

Issue with jQuery 'on' event not triggering following 'load' event

I am facing an issue on a page where similar events occur but when new content is loaded halfway through, most of the jQuery functionalities stop working. The scenario involves answering questions in a 'game' format using AJAX calls. Once all que ...

What is the process for selecting and clicking a specific div with a distinct class name in HTML

Hey there! I'm a beginner at coding with puppeteer and I have a question. How can I make my code click on this image: (image) The current code I have looks like this: const puppeteer = require('puppeteer'); (async () => { const bro ...

Error in delete operation due to CORS in Flask API

After successfully developing a rest api in Flask and testing all api endpoints with Postman, I encountered an issue while working on an application in Javascript that consumes the resources of my api. The problem lies in consuming an endpoint that uses t ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Can you please specify the type of values being entered as input?

Query: How do I identify the data type of the value entered in an input field? Whenever I use typeof, it always returns string unless the string is empty. I searched various forums extensively but couldn't find a solution. Can someone assist me with t ...

Animating elements within a D3.js force layout

I am looking to create a unique data visualization that resembles floating bubbles with text inside each bubble. Currently, I have a prototype using mock data available here: JSfiddle // Here lies the code snippet // ... However, my current challenge li ...