Struggling to establish a connection with AngularJS

I recently got my hands on the AngularJS SPA template for Visual Studio and dove straight into my first application. However, I'm already encountering a multitude of issues!

Here's a glimpse of my PersonView :

<!DOCTYPE html>

<html ng-app="app">
<head>
<meta name="viewport" content="width=device-width" />
<title>Add Person</title>
<script src="~/Scripts/vendor/angular.js"></script>
<script src="~/Scripts/app.js" type="text/javascript"></script>
<script src="~/Scripts/controllers.js"></script>

</head>
<body ng-controller="PersonCtrl">
<form name="A" ng-controller="PersonCtrl">
    <div class="row" >
        <div class="col-md-2">
            First Name:
        </div>
        <div>
            <input type="text" name="input" ng-model="$firstName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>
</form>
<form name="B" ng-controller="PersonCtrl">
    <div class="row" >
        <div class="col-md-2">
            Middle Name:
        </div>
        <div>
            <input type="text" name="middleName" ng-model="$middleName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>

</form>
<form name="C" ng-controller="PersonCtrl">
    <div class="row" >
        <div class="col-md-2">
            Last Name:
        </div>
        <div>
            <input type="text" name="lastName" ng-model="$lastName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>
</form>

<br />

Name :  {{firstName + middleName + lastName}}

Here is my Controller class :

'use strict';

// Google Analytics Collection APIs Reference:
// https://developers.google.com/analytics/devguides/collection/analyticsjs/

angular.module('app.controllers', [])

// Path: /
.controller('HomeCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window)
{
    $scope.$root.title = 'AngularJS SPA Template for Visual Studio';
    $scope.$on('$viewContentLoaded', function () {
        $window.ga('send', 'pageview', { 'page': $location.path(), 'title': $scope.$root.title
 });
    });
}])

// Path: /about
.controller('AboutCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window) {
    $scope.$root.title = 'AngularJS SPA | About';
    $scope.$on('$viewContentLoaded', function () {
        $window.ga('send', 'pageview', { 'page': $location.path(), 'title': $scope.$root.title });
    });
}])

// Path: /login
.controller('LoginCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window) {
    $scope.$root.title = 'AngularJS SPA | Sign In';
    // TODO: Authorize a user
    $scope.login = function () {
        $location.path('/');
        return false;
    };
    $scope.$on('$viewContentLoaded', function () {
        $window.ga('send', 'pageview', { 'page': $location.path(), 'title': $scope.$root.title });
    });
}])

.controller('PersonCtrl', ['$scope', function($scope) {
    //$scope.$root.title = 'Create Person';
    $scope.firstName = 'Aditya';
    $scope.lastName = 'Swami';
    $scope.middleName = ' ';

}])

// Path: /error/404
.controller('Error404Ctrl', ['$scope', '$location', '$window', function ($scope, $location,      $window) {
    $scope.$root.title = 'Error 404: Page Not Found';
    $scope.$on('$viewContentLoaded', function () {
        $window.ga('send', 'pageview', { 'page': $location.path(), 'title': $scope.$root.title });
    });
}]);

And here's my App.js

'use strict';


 angular.module('app', ['ui.router', 'app.filters', 'app.services', 'app.directives',  'app.controllers'])

// Gets executed during the provider registrations and configuration phase. Only providers and constants can be
// injected here. This is to prevent accidental instantiation of services before they have been fully configured.
.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {

    // UI States, URL Routing & Mapping. For more info see: https://github.com/angular-ui/ui-router
    // ------------------------------------------------------------------------------------------------------------

    $stateProvider
        .state('home', {
            url: '/',
            templateUrl: '/views/index',
            controller: 'HomeCtrl'

        })
        .state('about', {
            url: '/about',
            templateUrl: '/views/about',
            controller: 'AboutCtrl'
        })
        .state('login', {
            url: '/login',
            layout: 'basic',
            templateUrl: '/views/login',
            controller: 'LoginCtrl'
        })
        .state('person', {
            url: '/PersonView',
            layout: 'basic',
            templateUrl: '/views/PersonView',
            controller: 'PersonCtrl'
        })
        //.state('otherwise', {
        //    url: '*path',
        //    templateUrl: '/views/404',
        //    controller: 'Error404Ctrl'
        //});

    $locationProvider.html5Mode(true);

}])


.run(['$templateCache', '$rootScope', '$state', '$stateParams', function                                                                       ($templateCache,$rootScope, $state, $stateParams) {

    // <ui-view> contains a pre-rendered template for the current view
    // caching it will prevent a round-trip to a server at the first page load
    var view = angular.element('#ui-view');
    $templateCache.put(view.data('tmpl-url'), view.html());

    // Allows to retrieve UI Router state information from inside templates
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    $rootScope.$on('$stateChangeSuccess', function (event, toState) {


        // based on which page the user is located
        $rootScope.layout = toState.layout;
    });
}]);

Check out my solution structure below :

Answer №1

Consider using the variable firstName instead of $firstName:

 <input type="text" name="input" ng-model="firstName" ng-pattern="word" ng-required="true" />

Revise your layout to be more concise and efficient, without multiple forms and controllers:

<body ng-controller="PersonCtrl">

    <div class="row" >
        <div class="col-md-2">
            First Name:
        </div>
        <div>
            <input type="text" name="input" ng-model="firstName"
                   ng-required="true" />

        </div>
    </div>

    <div class="row" >
        <div class="col-md-2">
            Middle Name:
        </div>
        <div>
            <input type="text" name="middleName" ng-model="middleName"
                    ng-required="true" />

        </div>
    </div>


    <div class="row" >
        <div class="col-md-2">
            Last Name:
        </div>
        <div>
            <input type="text" name="lastName" ng-model="lastName"
                    ng-required="true" />

        </div>
    </div>

Furthermore, it is suggested to remove the entire code for $templateCache as it may not be necessary.

Answer №2

Your file contains redundant information that is already included in the parent file.

All unnecessary content should be removed. If you did not post the entire file, make sure to exclude the </body> and </html> tags at the end of the file.

<!DOCTYPE html>

<html ng-app="app">
<head>
<meta name="viewport" content="width=device-width" />
<title>Add Person</title>
<script src="~/Scripts/vendor/angular.js"></script>
<script src="~/Scripts/app.js" type="text/javascript"></script>
<script src="~/Scripts/controllers.js"></script>

</head>
<body ng-controller="PersonCtrl">

Furthermore, the file nests a controller that is already defined in the route, so the use of ng-controller is redundant and not necessary.

Consider whether multiple form tags are needed. In most cases, wrapping the entire page with one form is sufficient.

EDIT

It is recommended to prefix bound controller fields with $.

Here is a revised version of how the complete file should be structured:

<form name="MyForm" novalidate>
    <div class="row" >
        <div class="col-md-2">
            First Name:
        </div>
        <div>
            <input type="text" name="input" ng-model="firstName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>

    <div class="row" >
        <div class="col-md-2">
            Middle Name:
        </div>
        <div>
            <input type="text" name="middleName" ng-model="middleName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>

    <div class="row" >
        <div class="col-md-2">
            Last Name:
        </div>
        <div>
            <input type="text" name="lastName" ng-model="lastName"
                   ng-pattern="word" ng-required="true" />

        </div>
    </div>
</form>

<br />

Name :  {{firstName + middleName + lastName}}

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

What strategies can I use to reduce duplication in my HTML and JavaScript code?

Struggling with messy HTML and JS code? If you're using Bootstrap-3 and jQuery-1.11.0, dealing with dropdowns might be tricky. Especially when it comes to switching icons based on the dropdown state and ensuring only one dropdown is open at a time. Is ...

In TypeScript/Angular, what is the best way to share model variables between a Service class and a controller class?

Is there a way for the Controller and Service classes to access the same model without explicitly passing it? For example: Controller Class : import { SearchModel } from "../../models/SearchModel"; import { SearchService } from "../../components/SearchS ...

Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) { var tipPercent; if (bill < 50 ) { tipPercent = .20; } else if (bill >= 50 && bill < 200){ tipPercent = .15; } else { tipPercent = .10; } return tipPercent * bill; } var bills = ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

Identifying a loop within a hierarchy of JavaScript elements

I am facing a challenge with a list of elements that have unique IDs and parent IDs. My goal is to identify any loops in this hierarchical structure and pinpoint the ID that initiates the loop. list = [ { id: '1', parent: '2' ...

Creating custom directives that utilize recursive behavior within an ngRepeat loop

I am in the process of building a treeview using AngularJS. Below is the code I have so far: module.directive('treeview', function () { return { restrict: 'E', templateUrl: "/templates/ui/controls/treeview.htm", ...

Issues encountered with URL Rewrite functionality in IIS version 10.0

Currently utilizing URL Rewrite on IIS 10.0 with a rule set up at the server level (applicationHost.config). I have also attempted to implement this in my web.config without success. <rewrite> <globalRules> <rule name="redirect" ...

What is the best way to integrate JavaScript and Python for seamless collaboration?

I'm looking to create a bidirectional communication model between JavaScript and Python. The idea is for JavaScript to handle data processing, send it to Python for further processing, and then receive the results back from Python. However, I'm u ...

executing a series of jQuery ajax calls iteratively

In my Web Application, I have implemented "Spatial Selection" on a map that allows users to select multiple streets. Once selected, each street is assigned a unique Street Id through the use of a "Selection Handler". The next step in the process involves ...

Utilizing the power of AWS Lambda in conjunction with moment JS to generate unique

My current time zone is GMT+8, and the AWS region I am using is Singapore (ap-southeast-1). I am facing an issue where there are discrepancies in date calculations between my local machine and when I deploy my code on AWS Lambda. My goal is to ensure that ...

Guide on submitting form information to API controller

When using jQuery, form data is posted: $.ajax('API/Validate/Customer?column=1&rowid=2&vmnr=3&isik=4', { data: JSON.stringify({ headerData: $("#_form").serializeArray() }), async: false, cont ...

What is the process for including a checkbox with a label in Card Media?

I attempted to create this feature using code. However, I encountered an issue where the CardMedia and the checkbox would not align properly, resulting in a lack of responsiveness. <Card> <CardMedia ...

Retrieving property values from an object across multiple levels based on property name

I have a complex object structure that contains price information at various levels. My goal is to retrieve all values from the Price property, regardless of their nesting within the object. var o = { Id: 1, Price: 10, Attribute: { Id: ...

Can a class property's default value be determined by another property's value?

I am currently working with a list that includes a Value property and a CharToRead property. My goal is to automatically set the value of CharToRead to be equal to the length of Value. I have been contemplating using a constructor to achieve this, but I a ...

Establishing the httppostedfilebase variable when validation is unsuccessful in an ASP.Net MVC view

I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBa ...

Is it possible to delete and substitute all content following a specific DIV tag?

Is there a way to utilize JavaScript or jQuery to remove all content following a specific div element and insert new code? The div elements are generated dynamically, and I need to remove everything after the last div that looks similar to: & ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

Exception occurs when arrow function is replaced with an anonymous function

Currently, I am experimenting with the Angular Heroes Tutorial using Typescript. The code snippet below is functioning correctly while testing out the services: getHeroes() { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } H ...