Unable to attach scope variables in AngularJS

I currently possess the following files:

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Gestore Anagrafica</title>
</head>
<body>
    <div>
        <h3>Insert new person</h3>
        <div ng-app="Person" ng-controller="PersonController">
            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            Age: <input type="number" ng-model="age"><br>
            <br>
            Full Name: {{fullName()}} <br>
            Is major: {{isMajor()}} <br>
            <button ng-click="add()">Add Person</button>
        </div>
    </div>
    <script type="text/javascript" src="js/angular.js"></script>
    <script type="text/javascript" src="js/RegistryService.js"></script>
    <script type="text/javascript" src="js/PersonController.js"></script>
</body>
</html>

js/RegistryService.js:

angular.module('RegistryService', []).

service('registry', function()
{
    this.people = [];

    this.add = function(person)
    {
        people.push(person);
    }
});

js/PersonController.js:

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
    $scope.firstName = "testName";
    $scope.lastName = "";
    $scope.age = 20;

    $scope.isMajor = function()
    {
        return $scope.age > 18;
    };

    $scope.add = function()
    {
        registry.add({  'firstName': $scope.firstName,
                        'lastName': $scope.lastName,
                        'age': $scope.age});

    };

    $scope.fullName = function() 
    {
        return $scope.firstName + " " + $scope.lastName;
    };
}]);

The data binding seems to be faulty: any changes made to the name or age fields do not reflect in real-time. Additionally, upon loading, all input fields are blank although I expect to see 'testName' for firstName and '20' for age. The browser's console is clear of any errors. Am I overlooking something?

Constraints: It is mandatory for the service 'RegistryService' to exist in a separate file.

Question: Through the lines below:

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {

I am specifying that the module named 'Person' requires functionality from 'RegistryService' to operate properly. The controller 'PersonController' will utilize the 'registry' component defined within 'RegistryService'. Therefore, using anything undefined in 'RegistryService' would result in an error. Is my understanding of dependency injection accurate in this context?

Answer №1

It is crucial to include details about the $scope injection in your explanation, as it needs to be present in your controller function as the initial parameter:

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);

Answer №2

The $scope injection was not done correctly

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

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

Utilizing Angular Dependency Injection to Share Data Among Modules Through a Service

After reading about dependency injection in Angular, I decided to test it out. However, when trying to inject the module, I encountered an issue with passing values from one module to another and outputting them on the console. (Update: The issue has been ...

Conceal a div while revealing the other div

I am currently trying to achieve a unique visual effect. I have three divs named div1, div2, and div3. The objective is for div1 to slide up and disappear when clicked, while div2 simultaneously slides up and becomes visible. Similarly, when div2 is click ...

Selenium in C#: Timeout issue with SendKeys and Error thrown by JS Executor

Attempting to insert the large amount of data into the "Textarea1" control, I have tried two different methods. The first method successfully inserts the data but occasionally throws a timeout error, while the second method results in a JavaScript error. A ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

Differences between Creating and Updating Objects in JavaScript

When working with JavaScript, it is important to consider the best practices for performance optimization. Take a look at these two examples: Example 1: var x = {}; x.a = 10; Example 2: var x = {}; x = {a: 10}; Are there any noticeable differences in ...

Continuously unveil a circle in a repetitive sequence

I'm currently working on a project that involves a scanline effect, and I have a Codepen snippet displaying my progress (Codepen link). However, I want to take it a step further by gradually changing the color after the scanline has passed, similar to ...

Invoke a personalized filter in AngularJS using the controller

Trying to implement a filter on my controller for masking, specifically turning 348845697990 into 348.8456.979-90 has proven more challenging than expected. Take a look at the code snippets below: 1: Module setup: angular.module('webclientody', ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

Design an adaptive navigation bar with interactive dropdown options

I'm facing an issue with my responsive menu. While it works perfectly on desktop browsers, it behaves strangely on mobile browsers when I try to expand the sub-menu of the menu. After scrolling up and down, the menu tends to disappear. <style> ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Executing $(this).parent().remove() triggers a full page reload

A unique feature of my webpage is that with just a simple click of a button, users have the ability to dynamically add an endless number of forms. Each form contains fields for user input and also includes a convenient delete button. var form = " Name ...

Dragging and dropping files will not result in any redirection

My challenge involves working with a rectangle where I need to drop files. The issue is that when I try to drop them, the browser automatically redirects to the file location. While this behavior is expected, it interferes with my goal of uploading the fil ...

Submit the form with an input value that is located outside of the form

I am facing an issue with a dropdown menu that displays a list of users. When I select a user from the list, a radio button appears with options to Modify user details, Change user Permissions, or Warn User. After choosing an option from the radio buttons ...

JavaScript unable to dynamically change CSS styles

I've been struggling to get the color updates working for a while now. My suspicion is that my string return may be invalid, causing the issue. I'm aiming to convert hours, minutes, and seconds into hexadecimal values, but it seems to be failing ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

Is React dependent on the render process to update its state?

In my code, I am encountering an issue where the state of a key is not updating correctly even after performing operations on its value within a function. The scenario involves a function named clickMe, which is triggered by an onClick event for a button ...

Ways to attach a Javascript function to HTML content that is loaded dynamically

Utilizing the s3_direct_upload component, typically you would activate it by connecting your element to a function in either the ready or load event as shown below: $(function() { $('#s3-uploader').S3Uploader( { remove_completed_pr ...

NavigateToTop/BackToTheBeginning

I'm facing a challenge with a page layout that involves two vertical div's - one for the menu on the left and another for loading content on the right. My goal is to utilize the .scrollintoview() function on the menu div so that when a link is cl ...

Windows Keyboard Input Event

Is there a way to trigger an event using keyboard arrow keys on the page itself, without needing the mouse to be focused on an input or similar element? I attempted this but it didn't work as expected. handleKeyPress (e){ if(e.key == "ArrowLeft"){ ...