Exploring the capabilities of AngularJS for searching and modifying data

Currently, I am in the process of designing the user interface for a basic todo application. While my backend is already set up, I am encountering difficulties implementing the necessary functions on the front end. Specifically, I am struggling with adding a search and update feature to the app. Any assistance or guidance in this matter would be greatly appreciated.

index.js

function TodoCtrl($scope) {

  $scope.todos = [
    {id:1, text:'Mow the lawn',  selected:false},         
    {id:2, text:'Wash the car',  selected:false}
  ];

  $scope.getTotalTodos = function () {
    return $scope.todos.length;
  };


  $scope.addTask = function () {
    $scope.todos.push({text:$scope.text, id:$scope.id, date_created:Date.now, selected:false});
    $scope.text= '';
    $scope.id= '';
  };

  $scope.removeTask = function () {
    $scope.todos = _.filter($scope.todos, function(todo){
      return !todo.selected;
    });
  };

  $scope.showDetails = function(task_id) {
     var found = $filter('filter')($scope.todos, {id: task_id}, true);
     if (found.length) {
         $scope.selected = JSON.stringify(found[0]);
     } else {
         $scope.selected = 'Not found';
     }
  }


  $scope.updateTask = function (task_id) {
  // search $scope.todos for the item to update
  var indexOfTask;
  for(var i=0;i<$scope.todos.length;i++) {
     if($scope.todos[i].id===$scope.id) 
      indexOfTask = i;
      $scope.todos[i] = todo;
      $scope.todos.push();
      $scope.text= '';
      $scope.id= '';
  }

  // update the todo


};


}

index.html

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Todo App</title>
    <header>Todo App</header>


    <link rel="stylesheet" href="css/reset.css">


        <link rel="stylesheet" href="css/style.css">




  </head>

  <body>

    <html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="//use.edgefonts.net/vast-shadow:n4:all.js"></script>
    <script src="//use.edgefonts.net/vast-shadow:n4:all;megrim.js"></script>
  </head>
  <body>
    <div class="todo-wrapper" ng-controller="TodoCtrl">
      <h2>You have <span class="emphasis">{{getTotalTodos()}}</span> tasks</h2>
      <ul>
        <li ng-repeat="todo in todos">
          <input type="checkbox" ng-model="todo.selected"/>
          <span class="selected-{{todo.selected}}">{{todo.id}}: {{todo.text}} {{todo.date_created}}</span>
        </li>
      </ul>
      <form>
        <input class="add-input" placeholder="id" type="text" ng-model="id" ng-model-instant />
        <input class="add-input2" placeholder="task name" type="text" ng-model="text" ng-model-instant />
        <button class="add-btn" ng-click="addTask()"><h2>Add</h2></button>
        <button class="search-btn" ng-click="showDetails(task_id)"><h2>Search</h2></button>
      </form>
        <button class="update-btn" ng-click="updateTask(task)"><h3>Update Task</h3></button>
      <button class="clear-btn" ng-click="removeTask()">Remove Task</button>
    </div>
  </body>

</html>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js'></script>

        <script src="js/index.js"></script>




  </body>
</html>

Answer №1

For the best practice, consider including all relevant information about a to-do item directly within the ng-repeat loop to simplify referencing from the todos array.

To see the latest changes, you can check out the modified JSFiddle example or view the demo below. (I have commented out your CSS for easier debugging of the application.)

Additionally, ensure to implement ng-resource or a customized $http factory for performing server-side updates.

Your existing showDetails function with filtering should still work properly. I just integrated it within the ng-repeat loop for better visualization of filtered results.

angular.module('demoApp', [])
    .controller('todoCtrl', TodoCtrl);

function TodoCtrl($scope) {

    $scope.todos = [{
        id: 1,
        text: 'Mow the lawn',
        selected: false
    }, {
        id: 2,
        text: 'Wash the car',
        selected: false
    }];
    $scope.id = $scope.todos.length + 1; //will create UUID later

    $scope.getTotalTodos = function () {
        return $scope.todos.length;
    };

    // Other functions like addTask(), removeTask(), showDetails(), editTask(), save(), updateTask() goes here...

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp">
   <!-- Angular template -->

   <!-- Main todo tasks list and input form -->

</div>

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

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...

Is there a scope property that relies on a different scope property?

As a beginner in Angular, I could use some guidance on binding to scopes. I'm currently working on loading data that populates a property and then updating other properties based on this initial property. Is there an efficient way to trigger this pro ...

AngularJS $filter for searching and returning a specific item based on its unique identifier

Currently, I am attempting to search for a specific item within an array based on its ID. The ID is extracted from the URL, and I have tried using $filter method to achieve this. Below is the code snippet I have been working with: $filter('filter&ap ...

Get rid of the seconds in the output of the toLocaleTimeString

The method Date.prototype.toLocaleTimeString() provides a language-sensitive representation of the time part of a date in modern browsers. Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows ...

Could anyone lend a hand in ensuring that my AJAX call successfully processes the parameters?

When attempting to retrieve specific data from my database using AJAX, I encountered an issue where the call was successful when made through Postman or directly in the browser, but failed when initiated from my client. It seemed to work intermittently, re ...

What is the best way to alter the background of a div when hovering over a button in a separate div?

Looking to change the background of one div when hovering over a button in another div? Hello, I have a task where I need to modify the background color of a specific div when a button below it is hovered over. The setup involves having an image (a tshir ...

Stretch background image with html2Canvas in Chrome

I am currently using html2canvas to generate an image of a canvas with a background. It is working fine in Firefox, but in Chrome, the background is being vertically stretched. I am unsure of what the issue may be. Here is the link to my fiddle: http://j ...

Keep track of every JavaScript event happening in the browser console

Can all Javascript events be monitored? I am wondering whether there is an event that gets triggered after the DOM has been modified by an AJAX request. ...

Error: The function onSelect is not defined and cannot be executed by clicking on the HTML element with the id of "onclick" at line

I keep encountering this error message in my console: Uncaught ReferenceError: onSelect is not defined at HTMLAnchorElement.onclick (VM998 :14) This is the list data in my .html file: <ul class="nav navbar-nav"> <li& ...

Improve the efficiency of loading and utilizing data from the petition using $http

In my Ionic framework application, I am dealing with a large amount of data - around 10,000 records initially, with an additional 200 records being added every week. However, the loading time for this information is becoming a concern as certain sections o ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

Interactions with jQuery radio buttons

Currently immersing myself in the world of jQuery, I recently created a simple slider that has got me scratching my head. I'm trying to figure out how to properly attach events to radio buttons in a way that when clicked, my unordered list (ul) elemen ...

Could the slow loading time of the React site be attributed to an overload of static assets?

As a ML professional diving into frontend development, I have recently incorporated various fixed assets such as images into the assets folder for React. However, I've noticed that my website is running slower than expected. Do you believe that these ...

Generating a JavaScript bundle using the npm TypeScript compiler

Is there a way to compile TypeScript source files into one JavaScript bundle file? We have developed a tool on node.js and are currently using the following TypeScript compilation code: var ts = require('typescript'); ... var program = ts.creat ...

What is causing .attr('title') to retrieve the title of the element before?

UPDATE Flexslider now includes several callback spaces for use, making this functionality possible. after: function(){}, //Callback: function(slider) - Fires after each slider animation completes Thank you to everyone who contributed! LIVE CO ...

Updating the information displayed in one section by selecting a button on the Google Maps infowindow located in a separate section

My webpage is divided into multiple divisions. One division contains a map using the Google Maps API with markers. When I click on a marker, an info window opens up. Now, I am attempting to place a button inside that info window which, when clicked, will ...

Styling pagination using CSS and jQuery

I am looking to display 3 sections in a simple, paginated way that mimics tabs. I am trying to implement the logic where when a pagination item is clicked and has the 'active' class, it should show the corresponding block. However, I am strugglin ...

Personalize the jquery autocomplete outcome

I'm currently utilizing jQuery autocomplete along with a remote data source. $( "input#searchbar" ).autocomplete({ source: function( request, response ) { $.ajax({type: "post", mode: "abort", dataType: ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

what could be causing the token creation issue in node.js when implementing CSRF protection?

Can you explain why the token is not being created in node js CSRF? I have been using this npm package to generate and verify tokens: https://www.npmjs.com/package/csrf Here is the link to the code sandbox: https://codesandbox.io/s/quizzical-resonance-3y ...