简体   繁体   English

在模板中选择DOM元素

[英]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. 然后我想在每个模板范围内选择所有具有class="content"的元素,以便对其进行操作。 How can I achieve this using JS? 如何使用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 在此压板机中,console.log应该两次打印“ 1”,然后在第二次加载模板时打印“ 1”,然后打印“ 2”

After more explanation here is a working example: 经过更多说明后,这是一个有效的示例:

https://plnkr.co/edit/n5GOd6MDLyvG4ZAsuLvf?p=preview 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. 主要思想是创建2个列表并对其进行迭代,然后单击即可在它们之间移动数据。

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;
            }
          });
        }
  }]);

Most of the time you do not want to do DOM manipulation in Angularjs and instead hook into events with your controller. 大多数时候,您不想在Angularjs中进行DOM操作,而是使用控制器来挂接到事件。 If you have to do DOM manipulation in AngularJS you would use directives 如果必须在AngularJS中进行DOM操作,则可以使用指令
Docs on Creating a Directive that Manipulates the DOM 有关创建可操纵DOM的指令的文档

You could then use your link function to grab the children of your directive's element 然后,您可以使用link函数来获取指令元素的子级

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

https://stackoverflow.com/a/17329630/2033671 https://stackoverflow.com/a/17329630/2033671

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM