I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing?

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

angular.module('app').controller("MainController", function() {
  var vm = this;
  vm.ordered = [];

  vm.menu = [{
    title: 'Pizza',
    type: 'entree',
    favorite: true,
    price: 10
  }, {
    title: 'Tacos',
    type: 'entree',
    favorite: false,
    price: 5
  }, {
    title: 'Onion Rings',
    type: 'app',
    favorite: false,
    price: 2
  }, {
    title: 'Ice Cream',
    type: 'dessert',
    favorite: false,
    price: 11
  }, {
    title: 'Mac n Cheese',
    type: 'app',
    favorite: false,
    price: 7
  }, {
    title: 'Salad',
    type: 'salad',
    favorite: true,
    price: 4
  }];
}).directive('section', function() {
  return {
    restrict: 'E',
    link: function(scope, element) {
      scope.ordered = [];
      element.bind('click', function(event) {
        scope.ordered.push(scope.item)
      });

    }
  };
});;
.left {
  float: left;
  width: 50%;
}
.right {
  float: left;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body ng-app="app" ng-controller="MainController as main">

  <div class="left">
    <h2>Lists One</h2>
    <section id="{{item.id}}" ng-repeat="item in main.menu | filter:main.searchInput | orderBy:main.order.key:main.order.reverse">

      <strong>{{item.title}} </strong>
      <span>$ {{item.price}}</span>

    </section>
  </div>

  <div class="right">
    <h2>Lists Two</h2>
    <section id="{{item.id}}" ng-repeat="item in main.ordered | filter:main.searchInput | orderBy:main.order.key:main.order.reverse">

      <strong>{{item.title}} </strong>
      <span>$ {{item.price}}</span>

    </section>
  </div>

Answer №1

In response to your previous question, it is recommended to utilize ng-click instead of a directive.

If you simply want to add an item to the ordered list, you could use something like

ng-click="main.ordered.push(item)"
. However, this approach may lead to issues with duplicate items in the ordered list if the user clicks on an item multiple times.

Alternatively, you can create a function within your controller that performs tasks such as checking if the item is already in the ordered list, incrementing the quantity, updating the total price, etc. This can be achieved using ng-click="main.addToOrder(item)"

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

angular.module('app').controller("MainController", function() {
  var vm = this;
  vm.ordered = [];

  vm.menu = [{
    title: 'Pizza',
    type: 'entree',
    favorite: true,
    price: 10
  }, {
    title: 'Tacos',
    type: 'entree',
    favorite: false,
    price: 5
  }, {
    title: 'Onion Rings',
    type: 'app',
    favorite: false,
    price: 2
  }, {
    title: 'Ice Cream',
    type: 'dessert',
    favorite: false,
    price: 11
  }, {
    title: 'Mac n Cheese',
    type: 'app',
    favorite: false,
    price: 7
  }, {
    title: 'Salad',
    type: 'salad',
    favorite: true,
    price: 4
  }];
  
  vm.addToOrder = function(item) {
    if (vm.ordered.indexOf(item) > -1) { 
      // Logic for handling existing order items
    } else {
      vm.ordered.push(item);  
    }
  };
});
.left {
  float: left;
  width: 50%;
}
.right {
  float: left;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body ng-app="app" ng-controller="MainController as main">

  <div class="left">
    <h2>Lists One</h2>
    <section id="{{item.id}}" ng-repeat="item in main.menu | filter:main.searchInput | orderBy:main.order.key:main.order.reverse" ng-click="main.addToOrder(item)">

      <strong>{{item.title}} </strong>
      <span>$ {{item.price}}</span>

    </section>
  </div>

  <div class="right">
    <h2>Lists Two</h2>
    <section id="{{item.id}}" ng-repeat="item in main.ordered | filter:main.searchInput | orderBy:main.order.key:main.order.reverse">

      <strong>{{item.title}} </strong>
      <span>$ {{item.price}}</span>

    </section>
  </div>

Answer №2

Although I cannot confirm if this directly relates to your issue, it would be best to steer clear of directive titles that might overlap with HTML tag names.

The segment directive title you have chosen coincides with the existing HTML5 tag.

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

Utilize jQuery to target elements containing more than one class

Suppose an element has several classes as shown below: class="btn btn-primary add-movie-button is-on" Is it possible to select this element using only one class name with jQuery, for example: $(".add-movie-button") Can the method .hasClass("is-on") be ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

What are the best methods for improving the efficiency of a leaflet route

My map displays a path with more than 13,000 latitude and longitude points. When testing locally, everything works well. However, once the app is on a device, it becomes extremely slow and laggy. The density of the path is due to snapping it to roads. Wha ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Retrieve the host name using the getStaticProps method

Can the hostname be accessed within the getStaticProps function? export async function getStaticProps(context) { // retrieving the hostname const hostname = ???? } ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Emptying the AnyChart (Javascript) container prior to generating new charts

I have been utilizing the anychart JavaScript library to generate a pie-chart from my data, which is dynamically pulled whenever a user modifies a dropdown selection. Below is the code snippet I am employing for this purpose: var stage = anychart.graph ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

What could be causing my $resource error handler not to be invoked even though I have a responseError interceptor set up?

As I develop my first Angular application, I've encountered a challenge. Within my AngularJS resource, I call the .get method with both success and error callbacks, like this: var new_uptime = Uptime.get({}, function(){ console.log("new_uptime", ...

Failed commitments in Protractor/WebDriverJS

WebdriverIO and Protractor are built on the concept of promises: Both WebdriverIO (and as a result, Protractor) APIs operate asynchronously. All functions return promises. WebdriverIO maintains a queue of pending promises known as the control flow to ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays: "array_one": [ { "id": 1, "name": One }, { "id": 2, "name": Two } ] "array_two": [ { "id": 1, "name": Uno }, { "id": 3, "name": Three ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...