Utilizing multiple forms in AngularJS

As I delve into the world of AngularJS, I've managed to create a news page where users can comment on articles. However, I'm not entirely satisfied with the way I use classic JavaScript to dynamically fetch story forms. Is there a cleaner approach involving two-way data binding? My initial attempt resulted in the model being bound to both forms. What's the 'Angular' way around this issue?

Additionally, I've noticed that my form validation isn't functioning as expected. It seems like my initial attempt at it wasn't very successful.

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

        var _stories = [
        {
            Id: 1,
            Title: 'Man Falls Off The World!',
            Body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
            Date: '7 March 2015',
            Images: [],
            Comments: [{ Body:'LOL!', Name:'Michael', Date:'1 April 2015' }, { Body:'Tis a shame that.', Name:'William', Date:'1 April 2015' }]
        },
        {
            Id: 2,
            Title: 'Woman Eats Badger!',
            Body: 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
            Date: '8 March 2015',
            Images: [],
            Comments: []
        }
        ];

        app.controller('StoryController', function($scope){

            $scope.pageTitle = 'Welcome to the StoryTime website!';

            //  Initialize the story and blank Comment property here
            this.Stories = _stories;

            this.addComment = function(story){
                //  Refactor this section??
                var commentValue = document.getElementById('txtComment_' + story.Id);  
                var nameValue = document.getElementById('txtName_' + story.Id);  

                //  Create the object that holds the new comment value  
                var myNewComment = { 
                    Body: commentValue.value, 
                    Name: nameValue.value,
                    Date: '1 May 2015'
                };

                //  Add the comment to the array
                story.Comments.push(myNewComment);
                commentValue.value = '';    
                nameValue.value = '';            
            };
        });

<body ng-controller='StoryController as storyCtrl'>

<h1>{{pageTitle}}</h1>

<!-- Alias the controller for use in this section -->
<div ng-repeat="story in storyCtrl.Stories">

    <!-- For each Story, detail and show it -->        
    <h2>{{story.Title}} </h2>
    <h3>{{story.Date | date:'medium' }}</h3>
    <p>{{story.Body}}

    <div ng-repeat="comment in story.Comments">
        <h4>{{comment.Name}} - {{comment.Date | date:'medium'}} </h4>
        <em>"{{comment.Body}}"</em>
    </div>    

    <!-- Show and hide an introduction depending on if a story has a comment, or not -->
    <h4 ng-show="story.Comments.length > 0">Have a Comment? There are {{story.Comments.length}} comments made so far!</h4>
    <h4 ng-show="story.Comments.length == 0">Have a Comment? Be the first to comment on this excellent piece of journalism</h4>

    <!-- Start of the new form that holds the story's comments, we put the story's Id on all the HtmL so we can get this later, but i'm not sure if this is actually a good idea, yet. -->
    <form name="frmStory_{{story.Id}}" ng-submit="storyCtrl.addComment(story)">   
        Name: <br />
        <input id="txtName_{{story.Id}}" required /><br />    
        Comment:<br/>
        <textarea id="txtComment_{{story.Id}}" required></textarea>
        <button ng-disabled="frmStory_{{story.Id}}.$invalid">Add My Comment</button>
    </form> 
    <hr/>
</div>
</body>

Answer №1

ng-model plays a crucial role here. Each iteration of ng-repeat through a given collection creates a distinct scope for the corresponding piece of repeated HTML code according to the designated object. Utilizing ng-model enables you to manage the data within that specific scope.

<form name="frmStory_{{story.Id}}" ng-submit="storyCtrl.addComment(story)">   
    Name: <br />
    <input ng-model="story.newComment.Name" required /><br />    
    Comment:<br/>
    <textarea ng-model="story.newComment.Body" required></textarea>
    <button ng-disabled="frmStory_{{story.Id}}.$invalid">Add My Comment</button>
</form>

Additionally, in your code:

this.addComment = function(story)

You are referring to the instance of the controller. A more effective approach would be to bind everything related to the view with $scope.

$scope.addComment = function(story)

For further information on ng-model, visit: https://docs.angularjs.org/api/ng/directive/ngModel

Gaining an understanding of the Angular model and scope system is a significant milestone in grasping the Angular methodology for app development. I strongly encourage you to begin with that.

Answer №2

To create functions in your controller, follow this structure:

$scope.newFunction = function () {

}

For additional guidance, visit: https://docs.angularjs.org/guide/controller

If you are encountering form validation errors, could you provide the specific error messages for further assistance?

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

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...

The proper usage of middleware in vue-router

I've set up routes in Vue and added some middleware conditions before each route, but it's not functioning as expected. Below is the content of my router/index.js file: const token = computed(() => useAuthStore().token); // Main Router cons ...

Utilizing JSON to display multiple markers on a Google Map

How can I display multiple markers on a Google Map using JSON data? I have successfully added a single marker, but I'm facing issues with adding multiple markers. Below is the code for a single marker (which is working): var lat=position.coords.lati ...

NodeJS application does not acknowledge the term "Require"

I have completed the steps outlined on http://expressjs.com/en/starter/installing.html to set up my express NodeJS application. Following the installation, we navigated to the "myapp" directory and installed the "aws-iot-device-sdk" from https://github.com ...

select2 typeahead options for preloaded data

Utilizing Select2 on a select menu presents a challenge where the search field displays options even if the typed letters appear in the middle of an option. As an example, consider a select menu with options for Apple, Grape, and Prune: <select id="e1 ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

A guide to activating tag selection within the DevExtreme tag box

I'm currently utilizing devExtereme within my Angular project. My goal is to enable the selection of text within tags in my tagbox component. Here's what I have implemented: <dx-tag-box [dataSource]="sourves" [value]="value&quo ...

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

`Assemble: Store the newly created Stripe "Client Identity" in a designated container`

Upon a new user registration on my website, I aim to create a Stripe customer ID along with username and email for database storage. The process of customer creation seems to be working as evidenced by the activity in the Stripe test dashboard. However, h ...

Exploring Shadertoy's Visual Magic with THREE.js

I am currently attempting to implement this shader on a canvas using THREE.js: . The function I am using usually works for simpler shaders, but for this one, I might need to save the floats as uniforms. I am a bit stuck on this issue. Has anyone encounte ...

Code-based document editing with CouchBase

To test Couchbase, I need to create a servlet that will edit 1,000 JSON documents by changing the value of '"flag": false' to '"flag": true'. How can I achieve this task? Here is my view code for finding documents with '"flag": fa ...

Encountering a syntax error while transferring information from Ajax to PHP

I am currently experiencing an issue with my Ajax and PHP setup. Upon checking the browser console, I encountered the following error message: The following error occured: parsererror SyntaxError: Unexpected token <. Despite multiple attempts at debugg ...

Displaying files from Google Drive on a web page

How can I display documents saved on my drive on a webpage with the ability for users to download them directly? Any advice on how to achieve this would be greatly appreciated. Thank you! ...

The bootstrap function for showing the modal with the ID "myModal" is malfunctioning

As someone who is just getting started with PHP and Bootstrap, I am running into an issue where the modal doesn't seem to work when triggered using the .modal method. Here is the PHP code I am using: if ($show_login_modal) { echo " <scr ...

Can you create a dropdown menu using information from one JSON file and have the selected option come from another source?

Recently, I came across this JavaScript code that is supposed to create a dropdown list of statuses: $.getJSON('/statuses', { ajax: 'true' }, function (data) { var html; var len = data.length; html + ...

Using an object as a parameter in a NodeJS function

This past week, I encountered a challenge that has been difficult to overcome. I've been attempting to pass a JSON object as a parameter in a function, but I keep receiving an error message stating that it's not possible. Unfortunately, I don&apo ...

Extracting deeply nested values from a local variable within a view

Here is my current view: <p type="text" disabled='true' class="form-control" > {{selected.timerange}} </p> The value stored in $scope.selected.timerange is: {"available":false,"schedule_start_at":"2015-03-13T00:30:00","schedule_ ...

Error encountered: expected application router to be connected

I encountered an error while trying to migrate from next 12 to next 13 on my old project. Check out the Console Error Log Despite looking for faults in my code, I couldn't find any reason for these errors. Even after extensive Googling, no solution ...