Search code examples
javascriptangularjsangularjs-scope

Select DOM elements within template


There's this template that I call multiple times 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>

and then I want to select all the elements with class="content" within each template scope in order to manipulate them. How can I achieve this using JS?

EDIT :

Plunker

In this planker the console.log should print "1" twice and its printing "1" and then "2" when the template loads the second time


Solution

  • After more explanation here is a working example:

    https://plnkr.co/edit/n5GOd6MDLyvG4ZAsuLvf?p=preview

    The main idea is creating 2 lists and iterating over both and just moving data around between them on click.

    angular.module("demo", []);
    
    angular
      .module("demo")
      .controller("demoController", ["$scope", function($scope) {
    
      }]);
    
    angular
      .module("demo")
      .controller("templateController", ["$scope", "$timeout", function($scope, $timeout) {
                $scope.sourceList = [
                {
                    name: "john",
                    ID: 1
                },
                {
                    name: "Edward",
                    ID: 0
                },
                {
                    name: "Carl",
                    ID: 2
                }
            ];
    
            $scope.receiverList = [
                {
                    name: "Bob",
                    ID: 1
                }
            ];
    
            $scope.moveToReceiver = function(item){
              $scope.receiverList.push(item);
    
              $.each($scope.sourceList, function(i){
                if($scope.sourceList[i].name == item.name){
                  $scope.sourceList.splice(i, 1);
                  return false;
                }
              });
            }
      }]);