Ensure that you accurately maintain object ids following the creation of elements using ng-repeat

I have a set of items listed with unique objects within my controller

$scope.itemsList = [
    {"id": 0, "item": "sw", "category": 'A' },
    {"id": 1, "item": "mlr", "category": 'B'},
    {"id": 2, "item": "lvm", "category": 'C'},
    {"id": 3, "item": "ltc", "category": 'D'},
    {"id": 4, "item": "fr", "category": 'E'},
    {"id": 5, "item": "cap", "category": 'F'}
];

Using ng-repeat in my HTML to display them

<li ng-repeat="item in itemsList" ng-click="selectItem(item.id)"></li>

I can track the clicked item using $scope.selectItem triggered by ng-click. This is straightforward.

But what if later on, in a directive, an event is triggered? How do I extract information from the element, such as the original object id it belongs to?

// When a draggable item is grabbed
ums.directive('draggable', function (){

return function ($scope, element, attr){
    
    var el = element[0];
    el.draggable = true;

    el.addEventListener(
        'dragstart',
        function(e) {
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('Text', this.id);
            this.classList.add('drag');

            // My goal here is to retrieve the corresponding object id from $scope.itemsList when this event is fired
            console.log(el.$scope.item.id); // my initial thought

            return false;
        },
        false
    );

}

})

Answer №1

When using the ng-repeat directive, a new scope is created for each item added to the DOM. These scopes have specific properties set by the ng-repeat directive.

According to the documentation:

The ngRepeat directive generates a template for each item in a collection. Each instance of the template has its own scope, where the loop variable represents the current item in the collection and $index represents the index or key of the item.

Each scope inherits from the $parent scope. In your directive's linking function, you can access the original item using

scope.$parent.devices[scope.$index]
, but it is also available in the local scope.

For more details, refer to the AngularJS ngRepeat API Reference.

Example Update

This example demonstrates the directive retrieving the $index and triggering a custom event that the controller can utilize.

The directive

ums.directive('draggable', function (){
    function postLinkFn (scope, elem, attr){
        console.log("instantiating directive");

        elem.prop('draggable', true);

        elem.on ('dragstart',
            function(e) {
                elem.addClass('drag');
                console.log("dragstart index =", scope.$index);
                //emit event for controller
                scope.$emit("umsDragstart", e);
                return false;
            }
        );
    }
    return postLinkFn;
})

In the controller

    $scope.$on("umsDragstart", function ($event, rawEvent){ 
         console.log($event);
         console.log(rawEvent.x, rawEvent.y);
         console.log("umsDragstart id =", $event.targetScope.device.id);
    });

It's worth noting that the example utilizes jqLite methods on the elem parameter within the postLinkFn. Further information about these methods can be found in the AngularJS angular.element API Reference.

The $on and $emit methods are documented in the AngularJS $rootScope.scope API Reference - $on and API Reference - $emit.

Answer №2

In the scenario where the directive is being utilized within the controller that contains the selected() function, you have the option to assign the id to a scope variable and retrieve it within the directive. Alternatively, if you are incorporating the directive within an ng-repeat, you can establish a custom scope variable for the directive and pass the current id to it. Otherwise, feel free to provide a code sample as an illustration.

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

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Data within object not recognized by TableCell Material UI element

I am currently facing an issue where the content of an object is not being displayed within the Material UI component TableCell. Interestingly, I have used the same approach with the Title component and it shows the content without any problems. function ...

How can we redirect to another page after checking a box?

In the scenario where a checkbox is checked, how can the page be automatically redirected to @habit, simulating the behavior of clicking a submit button? habits/show <% if @habit.current_level_strike %> <div class="btn" id="red"> <l ...

How can I change a PHP for loop to Javascript?

Can the following code be converted to JavaScript? for (let lift of liftDetails) { document.write('<option>'+ lift["LiftMakes"] +'</option>'); } ...

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

Is JavaScript generating a random sequence by dynamically adding fields?

I'm encountering an issue with my button that adds a set of text fields every time I click on the Add More button. The problem is that when I add new text fields, they are appended above the Add More button. Then, pressing the button again adds more t ...

Show different material ui TextFields based on what the user chooses

My dropdown menu offers two options: BUY x AND y AND z SAVE m BUY n FOR m If I select option 1, I want to display Textfields for x, y, and z. If I choose option 2, then only Textfields for n and m should be displayed for user input. In the code snippet ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

Removing the gridlines in a Linechart using Apexcharts

I am experiencing issues with the grid and Nodata options on my Apexchart line chart. noData: { text: none , align: 'center', verticalAlign: 'middle', offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: &apo ...

Is it possible to utilize the WebGL camera in order to create dynamic transitions between various polygons?

Recently, a friend suggested exploring WebGL as an alternative to CSS transitions. I have a collection of polygons that form a 2D board game. In essence, the application moves the player space by space starting at the top of the "C", and we aim to create ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

Enhance your user interface with an interactive Bootstrap dropdown using Angular

I have a program where users can choose from 3 options such as: Hi, Hello and Hey. Currently, when a user selects one of the values, they receive a message saying that they need to "select a value." I am struggling to figure out how to update the ng-model ...

The file reader feature is currently experiencing issues on both Chrome and Internet Explorer browsers

After uploading an image file from my PC, I convert it to a data URL and then use the img element to preview it. Surprisingly, this process works perfectly fine in Firefox. However, when I try to do the same in Chrome or IE, the src attribute of the img el ...

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Identifying the moment a member receives a role using my Discord bot built with discord.js

I am currently working on detecting when a user is assigned a specific role on a server. Here is the code I have been using: // Require the required discord.js classes const { token } = require('./config.json'); // Create a new client instance ...

sending the AJAX request from back to the original JavaScript function

Here presents an issue. I am dealing with an HTML Form that contains a submit button with an onclick=validationFunction(). When this button is clicked, the form values are passed to the mentioned function. Within this function, the form values undergo va ...

Filtering an array of <input> values in JavaScript based on the number of characters they contain

Can someone help me figure out why this JavaScript code isn't working as expected? The intention is to grab the input value from a text box (a string of words separated by spaces), convert it into an array, and then remove any words that are less than ...

Ways to obtain the output of an If/Else statement

It seems like I might be missing something, but I am unsure of how to extract the result from an else-if statement. Take this code snippet that I've been working on for example: In this scenario, the output would read "It's warm!", and what I wa ...

Preventing the $_POST action value from being altered to match the ajax page path

My current setup involves using php, jquery, and ajax to update a particular section. The ajax call is executed successfully, but I encounter an issue where the global $_SERVER[SCRIPT_NAME] changes to match the ajax path when the requested data is returned ...