Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to the ng-click method and in todos-data.js? Here is a snippet of my code:

In todos-data.js (I currently manually add tasks, but I want to add them from the form):

app.factory('todos', function () { return [
  {
      'title': 'Date with Julia', 'done': false, "type": { "name":
      "Personal", "gico": "heart" }, 'estimates': 3, "date": "11/11/2015"
    },
    {
      'title': 'Gym', 'done': false, "type": { "name":
      "Health", "gico": "tint" }, 'estimates': 2, "date": "12/11/2015"
    },
    {
      'title': 'Next steps in AngularJS', 'done': false, "type": { "name":
      "Learning", "gico": "book" }, 'estimates': 4, "date": "14/11/2015"
    },
    {
      'title': 'Meeting with Jan', 'done': false, "type": { "name":
      "Business", "gico": "usd" }, 'estimates': 1, "date": "15/11/2015"
    },
    {
       'title': 'Run errands', 'done': false, "type": { "name":
       "Personal", "gico": "heart" }, 'estimates': 6, "date": "16/05/2015"
    }
  ];
});

Below is the form with the button:

edit.tpl.html

<div class="panel-body">
<form name="f" data-ng-submit="addTodo()">
  <label for="title">Name:</label>
  <input class="form-control" id="title" name="newTodo" data-ng-model="formData.newTodo" required>
  <label for="type">Type:</label>
  <select class="form-control" id="type" name="type" data-ng-model="formData.type" required>
    <option ng-repeat="value in categories" value="value.name">{{value.name}}</option>
  </select>
  <label for="estimates">Estimated time:</label>
  <select class="form-control" id="estimates" name="estimates" data-ng-model="formData.estimates" data-ng-options="value + 'h' for value in [] | rangeTime:9:true" >
  </select>
  <label for="text">Date:</label>
  <input class="form-control" id="text" type="text" data-ng-model="formData.date" data-ng-date-picker="" name="date" required readonly="readonly">
  <br />
  <button class="btn btn-success" data-ng-disabled="f.$invalid" ng-click="addTodo()">Add  <span class="glyphicon glyphicon-ok"></span></button>
</form>

Answer №1

To achieve this functionality, it is necessary to develop a controller. Within this controller:

var app = angular.module('myApp');
app.controller('myController', function($scope){
    $scope.addTodo = function(formData){
         $scope.items = formData;
    }
});

After creating the controller, you can implement the display on the desired page by utilizing 'ng-repeat'.

Answer №2

If you want to implement a similar functionality in your project, you can create a factory and then define the method in your controller by injecting the factory. Here is an example:

app.factory('todos', function () {
        return {
            todoArr: [{
                'title': 'Date with Julia',
                'done': false,
                "type": {
                    "name":
                        "Personal",
                    "icon": "heart"
                },
                'estimates': 3,
                "date": "11/11/2015"
            }, {
                'title': 'Gym',
                'done': false,
                "type": {
                    "name":
                        "Health",
                    "icon": "tint"
                },
                'estimates': 2,
                "date": "12/11/2015"
            }, {
                'title': 'Next steps with AngularJS',
                'done': false,
                "type": {
                    "name":
                        "Learning",
                    "icon": "book"
                },
                'estimates': 4,
                "date": "14/11/2015"
            }, {
                'title': 'Meeting with Jan',
                'done': false,
                "type": {
                    "name":
                        "Business",
                    "icon": "usd"
                },
                'estimates': 1,
                "date": "15/11/2015"
            }, {
                'title': 'Run, Forest, Run!',
                'done': false,
                "type": {
                    "name":
                        "Personal",
                    "icon": "heart"
                },
                'estimates': 6,
                "date": "16/05/2015"
            }],

            addToList: function (title, done, name, Personal, icon, estimates, date) {
                this.todoArr.push({
                    'title': title,
                    'done': done,
                    'type': {
                        'name': Personal,
                        'icon': icon
                    },
                    'estimates': estimates,
                    'date': date
                });
        }
    };
    });

In your controller:

.controller("main", function ($scope, todos) {
  $scope.add = todos.addToList;

})

And in your HTML:

<button ng-click="add(title, done, name, Personal, icon, estimates, date)">Add</button>

There are more efficient ways to handle the parameters instead of passing them individually like this. You can use ng-model to get them from a form input easily.

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

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

The issue of req.file being undefined when using Multer in Node.js with Express Router

I have been working on incorporating File Upload capability utilizing multer and Express Router. I set up an endpoint /batch_upload using router.use in the following manner: api.js router.use( "/batch_upload", upload.single("emp_csv_data"), userCo ...

Determine the total of all the values displayed in the footer of a jQuery

I am looking to show the total amount in the footer of a jquery datatable. Below is a snapshot of my datatable: https://i.stack.imgur.com/z01IL.png Here is the code snippet for my jquery datatable: for (var i = 0; i < length; i++ ) { var patient = ...

Unable to modify $scope value within the directive

This special function triggers once ng-repeat is done iterating through the list using scope.$last: simpleSearchApp.directive('afterResults', function($document) { return function(scope, element, attrs) { if (scope.$last){ scope.windowHe ...

The window.open function is returning a null value after attempting to open the specified

Is there a way to prevent users from opening more than one IFrame window for my application? I have included the following code: <html> <head> <title>Testing Window Opening Limitation</title> <meta http-equiv="Content-Type" cont ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

I'm looking to automate a system response whenever a user inputs something - how can I achieve this using NodeJS and Socket

I'm looking to create a feature where, if a user enters a specific command, the socket.io will respond with a predefined message. For example: Input: !hi Output: hello! If anyone knows how to achieve this, I'd appreciate some guidance, tha ...

Angular Q for Beginners - Manipulating Service Results

After spending the entire day working on my inaugural Angular app, I have come across a fundamental query. My objective is to design a text field with two strings that describe the current URL route and action in the following format: You are on: {{urlRo ...

Discover the depth of a deeply nested array

I have a complex array structure that looks something like this: I am trying to determine the depth of this nested array, focusing on the element with the most deeply embedded children. let arr = [ { name: 'tiger', children: [{ ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

Tips for adapting my custom input component for compatibility with vee-validate?

I recently developed an input component for my Vue project and integrated it within my forms. My aim is to implement vee-validate for validating the inputs. Initially, I attempted to validate my component like any regular input field. However, upon encoun ...

Displaying information from database using AngularJS

How can I display data from a database on my webpage? This is the JavaScript code: $scope.save = function() { var data = { subject: $scope.composeStory.subject, body: $scope.composeStory.body } $http.post( "insert.php", { ...

Tips for updating the appearance of a ListItem with a click action

For my current project, I am using Material UI and React. One of my components is structured as follows: import React, { Component } from 'react'; import { List, ListItem } from 'material-ui'; import PropTypes from 'prop-types&apo ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

Running multiple server and client codes on node.js simultaneously

I'm exploring the idea of establishing a network of nodes on my computer that have dual functionality as both clients and servers. Each node should be able to execute its unique server code and client code, allowing it to send requests to its individu ...

Trigger the script upon clicking the Save button within the AdminBro Edit page

AdminBro's documentation mentions that they provide predefined actions Edit (record action) - update records in a resource They also offer a hook called after. I created a function and assigned it to MyResource.edit.after. However, the issue is tha ...

Accessing a specific element within an array that has been nested within another array, using JavaScript

Here's what my code looks like: planets[0]= new THREE.Mesh( geometry, material ); planettexts[0]= new THREE.Mesh( textGeometry, textMaterial ); planets[0].add(planettexts[0]); Now, I am trying to hide the planettext, but every attempt results in an ...

Cannot find a function within the Promise

Here is the code snippet I am working with: var c = function(address, abiJson){ var _ = this; this.data = { wallet: false, account:{ address: false }, contract:{ addre ...

Bringing in an external .js file into nuxt.config.js

Having trouble importing config.js with the project's API keys and getting undefined as a return value. //config.js var config = { fbAPI: "key" } - //nuxt.config.js const cfg = require('./config') env: { fbAPI: cfg.apiKey } Wonder ...