Struggling with creating a simple AngularJS controller

Apologies if my question seems basic, but I am currently learning about AngularJS controllers.

Below is the structure of my project:

https://i.sstatic.net/EQOel.png

Here is the snippet of my HTML code:

<!doctype html>
<html ng-app>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script src="js/controllers.js" />
</head>

<body>

<div ng-controller="numberController">
<input type = "text" ng-model = "number.number1" placeholder = "Enter a number here">

<input type = "text" ng-model = "number.number2" placeholder = "Enter another number here">
{{number.number1}} + {{number.number2}} = {{number.sumIt()}}

</div>
</body>
</html>

This snippet shows my controller implementation:

function numberController($scope) {
    $scope.number = {
        number1: 0,
        number2: 0,

        sumIt: function() {
            var numObj;
            numObj = $scope.number;
            return parseInt(numObj.number1) + parseInt(numObj.number2);
        }
    };
}

I'm facing issues with loading the webpage and seeking guidance on what could be wrong.

Upon further investigation, I received this error message: Error Message Link.

I made some updates to my controller as follows:

var saApp = angular.module("saApp", []);

saApp.controller('numberController', function($scope) {
    $scope.number = {
        number1: 0,
        number2: 0,
        sumIt: function() {
            var numObj;
            numObj = $scope.number;
            return parseInt(numObj.number1) +      parseInt(numObj.number2);
        }
    };
});

Additionally, here is an updated version of my HTML code:

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script src="js/controllers.js" />
</head>

<body>

<div ng-app = "saApp" ng-controller="numberController">
<input type = "text" ng-model = "number.number1" placeholder = "Enter a number here">

<input type = "text" ng-model = "number.number2" placeholder = "Enter another number here">
{{number.number1}} + {{number.number2}} = {{number.sumIt()}}

</div>
</body>
</html>

Answer №1

To start, make sure you have linked your application with your JS file. Update your tag to and update your controllers.js file accordingly.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.number = {
        number1: 0,
        number2: 0,
        sumIt: function() {
            var numberObject;
            numberObject = $scope.number;
            return parseInt(numberObject.number1) +      parseInt(numberObject.number2);
        }
    };
});
</script>

You can also access the console by right clicking with your mouse and selecting Inspect element.

Answer №2

Hello! Here is an example of how you can write your program:

<!doctype html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script>
 angular.module("myapp", [])
    .controller("NumberController", function($scope, $http) {
       $scope.number = {
        number1: 0,
        number2: 0,
        sum:0,
        sumIt: function() {
            var numberObject;
            numberObject = $scope.number;
            this.sum = parseInt(numberObject.number1) + parseInt(numberObject.number2);
        }
    };
    } );
</script>
</head>
<body ng-app="myapp"> 
<div ng-controller="NumberController">
<input type = "text" ng-model = "number.number1" placeholder = "Enter a number here"/>

<input type = "text" ng-model = "number.number2" placeholder = "Enter another number here"/>
<input type = "button" ng-click="number.sumIt()" value="Sum"/>
sum is {{number.sum}}

</div>
</body>
</html>

Answer №3

The issue at hand: you are currently utilizing an outdated method for declaring controllers. Starting from version 1.3, it is no longer possible to declare a controller using function <controller>.

To address this concern:

Step 1: Declare the application –

var app = angular.module('myApp', []);

Step 2: Attach the controller

app.controller('numberController', ['$scope', function($scope) {

$scope.number = {
        number1: 0,
        number2: 0,

        sumIt: function() {
            var numberObject;
            numberObject = $scope.number;
            return parseInt(numberObject.number1) + parseInt(numberObject.number2);
        }
    };
}]);

I have created a jsfiddle for demonstration purposes.

Answer №4

To start, you need to define the angular.module

<html ng-app="myApp">

Next, create your controller using the following syntax

var myApp = angular.module('myApp',[]);

myApp.controller('numberController', ['$scope', function($scope) {
   //Add your controller logic here
}]);

You can view a working example on codepen Here

Additional resources:
1 . Angular docs
2 . TutorialsPoint angular js

Answer №5

It seems like your code may be missing the definition of the app module. Referencing Angular documentation for guidance.

// app.js
    (function(angular) {
        angular.module('ngAppDemo', []).controller('NumberController', function($scope){
            $scope.number = {
                number1: 0,
                number2: 0,

                sumIt: function() {
                    var numberObject;
                    numberObject = $scope.number;
                    return parseInt(numberObject.number1) + parseInt(numberObject.number2);
                }
            };
        });
    })(window.angular);

You should note that the naming convention for Angular controllers is not being followed properly. The controller name should start with an uppercase letter, while the JavaScript function starts with a lowercase letter (e.g., function numberController() - ng-controller="NumberController")

Lastly, remember to include ng-app in the html or body tag and the controller on the div element.

<body ng-app="ngAppDemo">
    <div ng-controller="numberController">

Answer №6

var exampleApp = angular.module('exampleApp',[]);

exampleApp.controller('mathController',  function($scope) {
   //$scope.math ={};
  $scope.math = {
        num1: 10,
        num2: 0,

        calculateSum: function() {
            var mathObject;
            mathObject = $scope.math;
            return parseInt(mathObject.num1) + parseInt(mathObject.num2);
        }
    };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html >

<head>
   
</head>

<body ng-app="exampleApp">

<div ng-controller="mathController">
<input type = "text" ng-model = "math.num1" placeholder = "Enter a number here">

<input type = "text" ng-model = "math.num2" placeholder = "Enter another number here">
{{math.num1}} + {{math.num2}} = {{math.calculateSum()}}


</div>
</body>
</html>

Answer №7

I made some changes to your code to make it compatible with the existing directory structure. Here is the updated JavaScript file :

var app = angular.module('myApp', []);
app.controller('numberController', function($scope) {

        $scope.number = {
        number1: 0,
        number2: 0,

        sumIt: function() {
            var numberObject;
            numberObject = $scope.number;
            return parseInt(numberObject.number1) + parseInt(numberObject.number2);
        }
    }; 

});

And here is the revised HTML code :

<!DOCTYPE html>
<html ng-app="myApp">

   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   <script src="js/controllers.js" > </script>

<body>
    <div ng-controller="numberController">

       <input type = "text" ng-model = "number.number1" placeholder = "Enter a number here">

       <input type = "text" ng-model = "number.number2" placeholder = "Enter another number here">

        {{number.number1}} + {{number.number2}} = {{number.sumIt()}}

    </div>

</body>
</html>

Answer №8

What do you think of this design:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <div ng-controller="numberController as ctrl">
    <input type="number" ng-model="ctrl.number1" placeholder="Enter a number here">
    <br>
    <input type="number" ng-model="ctrl.number2" placeholder = "Enter another number here">
    <br>
    <div ng-if="ctrl.number1 && ctrl.number2">
      {{ctrl.number1}} + {{ctrl.number2}} = {{ctrl.sum(ctrl.number1, ctrl.number2)}}
    </div>
  </div>

</body>
</html>

Implementation using Javascript:

var myApp = angular.module('myApp',[]);

myApp.controller('numberController', function() {
  var vm = this;
  vm.number1 = null;
  vm.number2 = null;
  vm.sum = function(num1, num2) {
    return num1 + num2;
  };
});

Check out JS Bin example

It's recommended to utilize the 'controller as' syntax. In addition, consider utilizing a directive (or component if feasible on AngularJs 1.5) instead of employing ng-controller.

Answer №9

To implement this functionality in your controller:

let app = angular.module('myapp', []);

app.controller('numberController', function($scope) {
    $scope.number = {
        number1 : 0,
        number2 : 0,
        sumIt : function() {
            // you don't need to create a separate variable for $scope.number, just use it directly
            return parseInt($scope.number.number1) + parseInt($scope.number.number2);
        }
    };
});

Next, include the following HTML code:

<body ng-app="myapp">
    <div ng-controller="numberController">
        <input type="text" ng-model="number.number1" placeholder="Enter a number here"/>
        <br /><br />
        <input type="text" ng-model="number.number2" placeholder="Enter another number here"/>
        <br /><br />
        Total: {{number.sumIt()}}
    </div>
</body>

Finally, see the output here.

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

AngularJS Banner: Displaying Current Calendar Week and Increasing by 10 Days

I'm brand new to Angular and currently encountering some issues. Here's what I'm trying to create: I need to display the current Date: yyyy-MM-ss (Functional) I want to show the current Calendar Week: yyyy-Www (Not Working) When a butto ...

Make sure the inputs in separate table data cells are lined up in

I need help aligning two input fields in separate td elements to be on the same line. The issue I am encountering is that when an input is added to a td, it covers up any text within the td. https://i.stack.imgur.com/c7GiQ.png There are two scenarios: I ...

Should I utilize Sockets or Ajax for my project?

My Login Script Journey I have a goal in mind - to create a login script using Nodejs. I am currently exploring the options of utilizing sockets or ajax posts for this task. My Progress So Far I have Nodejs installed and have referenced this code in my ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

Guide on how to navigate to a different webpage once the ajax request is complete

When making a JQuery ajax call to invoke a void method, I have encountered the need to redirect the user to the home page upon successful login. Below is an example of how this can be achieved: var options = { url: "/Account/Login", data: formvalu ...

What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing ...

Tips for including HTML in a JSON request in ReactJS

Upon sending the request as shown below, the response was successfully received. { "contractId": "siva8978", "html": "<p>PREFERENCE SHAREHOLDER AGREEMENTTHIS AGREEMENT is made on the&nbsp;$$Contract Start Date$$ BETWEEN&nbsp;CRADLE WEALTH ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...

Concealing a hyperlink depending on the value chosen in a dropdown menu

Looking for guidance on how to use jQuery to read the current value of a drop-down list and hide a specific link based on that value. The drop-down list is for selecting the language/locale. For example, when "English" is selected, I want the link to be h ...

I am having trouble with updating my contacts

After studying various tutorials on the MEAN Stack, I decided to work on a project that is almost finished, except for an issue with my update function. Every time I try to update, I encounter a 400 error message. When I checked the response in the network ...

Jade: utilizing a Jade block within a Mixin by passing it as a string

I have come across a Jade template that includes a call to a mixin at a specific point. One of the parameters passed to this mixin is a lengthy HTML string which the mixin then prints using != The code looks like this: +createHTML({firstSection:'< ...

What is the best way to utilize the multiple orderBy filter with arrays in AngularJS?

Is there a way to properly implement multiple orderBy filters when filtering the list of an array in AngularJS? //here we create the product array and display the array in the HTML page. var app=angular.module("App",[]); app.controller("Cont",function( ...

Importing d3.JS JSON data without polluting the global scope

Here is a JSON object: { "temp_data": [10,15,20] } I'm trying to import it: var temp_data; //Importing from JSON if(true){ d3.json("graph.json", function(error, graph) { if (error){ throw error; } temp_da ...

NodeJS parseStream, setting boundaries for chunk extraction from a stream

Struggling with parsing Node's filesystem. Below is the code snippet in question: var fs = require('fs'), xml2js = require('xml2js'); var parser = new xml2js.Parser(); var stream = fs.createReadStream('xml/bigXML.xml&ap ...

Extracting dynamic content from a webpage using Selenium with Javascript rendering capabilities

Seeking a way to extract data that populates the SVG elements on a specific page: The page seems to be driven by JavaScript, making traditional BeautifulSoup methods in Python ineffective. After inspecting the network for XHR requests, it doesn't see ...

Is there a more concise way to write this code in JS, CSS, or HTML programming?

Seeking advice on JS / CSS / HTML programming! I may not be the best at articulating my question, so I apologize for any confusion. Let me clarify my intention behind this specific code section and explore potential solutions. The goal is to allow users ...

React and Redux Toolkit collaborated to create a seamless shared state management system,

Currently, I am developing a simple application to experiment with Redux Toolkit alongside React. Despite being able to view the object in the Redux Chrome tab, I am facing difficulties accessing it using React hooks within components. The code for my sli ...

Having trouble with the Material-UI v1 Drawer component on the iOS 13 beta version

As we prepare for the upcoming iOS release, set to debut next month, it has come to our attention that the main navigation on our website is experiencing issues when accessed using an iOS device running the latest beta (iOS13). While the drawer opens as ex ...

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

What steps can I take to incorporate additional arguments into my function?

I am currently working with NodeJS, express, and passport. However, I believe this question is specifically related to JavaScript. Within my routes file, I have the following code: app.get( '/users', login_req, user.index); So, when a get requ ...