Choose elements in the template's DOM

There is a specific template that I consistently reference on the same page:

<div ng-controller="templateController">
      <div class="source">
        <div ng-repeat="item in info">
            <div class="content" data-value="{{item.ID}}">{{item.name}}</div>
        </div>
    </div>
    <br style="clear:both" />
    <div class="receiver"></div>

</div>

I am looking to target all elements with class="content" within each instance of the template so that I can make changes to them dynamically. What is the best way to accomplish this using JavaScript?

EDIT :

Plunker

In the Plunker, the console.log should ideally output "1" twice, but instead it displays "1" first and then "2" when the second template loads.

Answer №1

Here is a functional code snippet with an explanation:

https://example.com/codeSnippet123

The concept involves managing two lists and transferring data between them upon a click event.

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

angular
  .module("app")
  .controller("mainController", ["$scope", function($scope) {

  }]);

angular
  .module("app")
  .controller("listController", ["$scope", "$timeout", function($scope, $timeout) {
            $scope.sourceList = [
            {
                name: "Alice",
                ID: 1
            },
            {
                name: "Eva",
                ID: 2
            }
        ];

        $scope.receiverList = [
            {
                name: "Emily",
                ID: 3
            }
        ];

        $scope.moveItemToReceiver = function(item){
          $scope.receiverList.push(item);

          $.each($scope.sourceList, function(index){
            if($scope.sourceList[index].name == item.name){
              $scope.sourceList.splice(index, 1);
              return false;
            }
          });
        }
  }]);

Answer №2

It is recommended in AngularJS to avoid direct DOM manipulation and instead utilize controller events for better application structure. However, when necessary, directives can be used for DOM manipulation.
Learn more about Creating Directives that Manipulate the DOM

To access children of a directive's element, you can use the link function.

function link(scope, element, attrs) {
    var content = angular.element(element[0].querySelector('.content'));
}

Check out this Stack Overflow post for additional insights

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

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

Angular's Routeprovider: Navigating Your Way through the

I am a newcomer to Angular and I encountered an issue while trying to implement routeProvider in my app. The error message that keeps appearing is: Uncaught Error: [$injector:modulerr] Failed to create module 'app' due to: Error: [$injector: ...

What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas. Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top ...

Using the comma separated values as the final parameter in the ng-repeat loop

In my select element, I am utilizing ng-repeat to generate options. My goal is to include a final option labeled All, which should display the comma-separated values of all the other options. <select ng-model="facilityIdForEquipment" ng-change="loadFa ...

Enhance Your Website with a jQuery Plugin for Dynamic Updates to ElementsgetPost

Is there a way to update the content inside an element by passing a new value to the public method updateText? Currently, when I try to pass a new string to the updateText method and click the button, only the method name is received as an argument instea ...

Generating consecutive numerical values within the auto table JSPDF column VusJs

https://i.sstatic.net/idhrw.png columns: [ { header: 'No', dataKey: 'Index', }, { header: 'No Registrasi', dataKey: 'no_register' }, { header: 'Kode Partai', data ...

How should filtering be properly done on a data array within a Redux reducer function?

I am trying to develop a function that filters an array based on a search input. The goal is for the filter action to trigger when there's a change in the SEARCH_TEXT. However, I'm facing confusion when it comes to handling the state when the del ...

Guide to setting up Firebase pagination in a NextJS 13 server component

Currently, I am working on developing a product page that showcases all products and functions as a server component. The challenge I am facing is the inability to pass the last visible document snapshot required by the startAfter() query. Below is the fu ...

Using JQuery to loop through JSON data and display it dynamically on a webpage

I am working with a JSON list that contains an array of "OrderLines" along with other data like part numbers and prices. My goal is to display each "OrderLine" and its corresponding data in HTML elements or tags. I want the HTML elements for each order li ...

Problems with Nested Loops in JavaScript

I have a nested loop structure that looks like this: var len = bolumlerUnique.length; function sendSections() { for (i = 0; i < bolumlerUnique.length; i++) { elementSections = $("[sectionid=" + bolumlerUnique[i] + "]:checked"); cons ...

Importing template Vue files into Router in Vue.js

Hello everyone, I have a Vue.js project that I am working on and I am looking to import a vue template file into my index.html without using webpack or browserify. It seems like I will need to use a router to accomplish this and include some additional Ja ...

Exploring the depths of nested ng-repeat using JSON structures

I am attempting to organize a nested loop with ng-repeat but I am encountering an issue where nothing is being displayed in the nested loop. HTML: <div ng-repeat="person in persons"> <p> {{ person.name }} </p> <div ng-repeat="frien ...

Discovering a specific value by locating a string in an array nested inside an object

Here is an example object that I need help searching: data = [ { type: "fruit", basket: ["apple", "pear", "orange"] }, { type: "vegetable", basket: ["carrot", "potato"] } ]; I am trying to find the item 'potato' and retu ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

Switch between Bootstrap Chevron

I need assistance with toggling a chevron in a bootstrap dropdown menu. Currently, the chevron only changes when clicked directly, but I want it to change whenever the dropdown is toggled open or closed. This way, if another part of the menu is clicked, th ...

Can a dropdown list be designed to appear as a box or div instead of the standard select option?

My idea is to use boxes to represent different options https://i.sstatic.net/rTmIj.jpg <label for="product">Choose:</label> <select name="product" id="product"> <option value="70A"> ...

Issue with binding the expanded property in Angular Expansion Panel

Including Angular code within my HTML, I have Admin and User Main menu items available. <a id="adminId" (click)="sideNavLink($event)">Admin</a> <mat-accordion class="mat-accordion-setting"> <mat-expansi ...

Interested in resizing the arrow from big to small?

I am currently using angular2-multiselect and I have noticed that the default size of the arrow is quite large. I am interested in reducing the size of the dropdown arrow. <angular2-multiselect class="form-control" [data]="dropdownList1" [(ngMo ...

The combination of WASM and Node.js encounters an issue when attempting to utilize 'import.meta' outside of a module

I successfully compiled the FastText C++ module to a wasm module using the provided make file, with the following flags: EMCXX = em++ EMCXXFLAGS = --bind --std=c++11 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPos ...