What is the best way to assign a distinct identifier to every ng-model within an ng-repeat loop?

I am encountering an issue with my page that includes multiple AngularUI sliders and a span displaying the value of each slider using ng-bind. The structure looks similar to this:

   <div class="formitem" ng-repeat="food in foodlist" >
     <div ui-slider="{range: 'min'}" min="0" max="{{ unit.max }}" ng-model="demoVals.slider" class="food-slider" >
      <div class="begin">1</div>
      <div class="end"> {{ unit.max }} {{ food.uid }}  </div>
    </div>
    <span ng-bind="demoVals.slider"></span>
   </div>       

I am aiming to make the ng-model unique for each food item, utilizing something like demoVals.slider57, where 57 is derived from {{ food.uid }}. While I can successfully display {{ food.uid }} in the template, trying to integrate it into ng-model or ng-bind yields results like this:

 ng-model="demoVals.slider[food.uid]"

How can I effectively incorporate the food.uid into the ng-model for each food item?

Answer №1

It may not be the most effective architectural decision to use individual elements instead of an array when dealing with slider values. Consider transitioning to storing your slider values in an array for better organization and efficiency.

If you're set on using individual elements, you can create a controller function to achieve your desired outcome, although it may not be the most visually appealing solution. Utilize the ng-repeat directive to bind to a function like so:

<div ng-bind="test(food.uid)"></div>

The corresponding function would look like this:

$scope.test = function test(v) {
        var t = $scope.$eval("demoVals.slider" + v);
        return t;
      };

Answer №2

If you want to include a food.uid property in demoVals during each iteration, you will need to run some JavaScript code for each iteration. This task can only be accomplished (in my opinion) using a directive.

To see it in action, check out this functioning Plunker.

The following is how you should adjust your HTML by adding the repeat-directive as shown below:

<div class="formitem" ng-repeat="food in foodlist" repeat-directive>
 <div ui-slider="{range: 'min'}" min="0" max="{{ unit.max }}" ng-model="demoVals.slider" class="food-slider" >
  <div class="begin">1</div>
  <div class="end"> {{ unit.max }} {{ food.uid }}  </div>
</div>
<span ng-bind="demoVals.slider"></span>

Additionally, here is the code for the directive that will be executed for every iteration:

var app = angular.module('plunker', [])
             .directive ('repeatDirective',function () {
                                           return {
                                              restrict: 'A',
                                              link: function (scope, element, attr) {
                                                console.log('linking directive ',scope.demoVals)
                                                 if (scope.food){
                                                   // you have a value for food
                                                   // you can add it as an attribute to demoVals
                                                   scope.demoVals['prop'+scope.food.uid] = scope.food.name;
                                                 }}
                                           }
                                          }); 

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

Employing regular expressions within Notepad++ to insert whole numbers into img src within table elements

I have a large table filled with numerous items that require individual images to be added. Let's take a look at the code snippet below. <tr><td><img src=".jpg" width=100 height=100/></td></tr> Although I could manually ...

Is there a way to make a div rotate from one of its ends rather than its center with atan2() method?

I want the div.stick in the following code to rotate based on a different origin point. Currently, it rotates from the center but I would like it to rotate from the bottom of the stick instead. The rotation should occur when the mouse is aligned with the t ...

Popup appears on incorrect page

As part of my app development project, I implemented a popover feature that opens when clicking on a label. Initially, this functioned smoothly within a tab navigation setup. However, after transitioning from tab modules to the app-routing module to displa ...

Every time I perform a POST request, there seems to be a blank space unexpectedly added

programming screenshot result screenshot why is there an extra space appearing after making a POST request using REST API? ...

Transmit information to Angular application upon being delivered by Express

I am currently working on an Angular application powered by Express 4.0. I am looking to send data to the front end during startup, specifically when the index file is being served. However, I am struggling to determine the most appropriate route to accomp ...

Issues with NGRepeat causing AJAX JSON errors

Facing an issue with displaying JSON data fetched from the server (Node.js) in NGrepeat. Various attempts have been made to troubleshoot using Firebug and Firefox Web Inspector. Despite the JSON data appearing correct when viewed in the Firebug console ( ...

Trouble accessing Silverlight site due to incomplete loading

There is a site known as that consists of a Silverlight application. Strangely, this site loads on all other computers except mine. I keep encountering the following error: An Error occurred in the Silverlight Application: String was not recognized as a ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to ...

Guide to executing a chain of parallel API calls with changing parameters using nodejs

I am working on a project that involves making multiple API calls while changing a single parameter value in the URL based on values stored in an array. Currently, I have about 30-40 values in the array and I am using NodeJS and Express for this task. Belo ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Creating concise AngularJS Controllers for form functionality

While working on a web project with AngularJS, I've observed that most of my form controllers share similar structures. For instance, the only difference between my login controller (as shown below) and a reset password controller is that instead of $ ...

Boosted - Automated Observable with controlled Update alert

Is there a way to create a ComputedObservable in knockout that is computed from non-observable values and manually trigger the Notification? ...

Issue with Ajax POST request: encountering a 500 internal server error

I am facing an issue with my project when I try to run it. Whenever I attempt to run the project, I encounter a 500 internal server error. Here is a snippet of my code: Client.cs public class Client { public Client(string firstName, string id ...

Utilize local storage to dynamically update the background color of a div section

Struggling to create a functionality on my website where users can input a color, save it to localStorage, and have a specific div's background set to that color across all pages. The main content div (with the same ID) needs to display this color con ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Tips for effectively refining an Angular model (array) without compromising its integrity

I am currently working with a model for my view. This model consists of an array of objects: var arr = { "12345qwery": { prop1: "value", prop2: "value" } } // consisting of 500 items When filtering this array today, I use the following method: arr = $ ...

The email was sent successfully using AJAX POST, however, the error callback was triggered instead of the success callback

When I send e-mails via AJAX, it successfully goes to the recipients. However, I'm puzzled as to why the success callback in AJAX is not triggered even though the e-mail has been sent. Instead, it triggers an error callback. It doesn't seem to b ...

Having issues with AngularJS routing functionality not functioning as expected

Currently, I am delving into AngularJS as part of a project I'm working on. Initially, AngularJS seemed like a promising framework, offering great support and user-friendly features. However, I have hit a roadblock when trying to implement routing... ...

Is there a way to incorporate an image, logo, and text into a 3D canvas?

https://i.sstatic.net/X7snd.png Recently diving into Three.js, I am faced with a challenge. I am attempting to display a 3D model in the canvas along with a logo and text message. However, when I try to capture the canvas using renderer.domElement.toDataU ...