在模板

时间:2017-10-20 15:27:32

标签: javascript angularjs angularjs-scope

我在同一页面上多次调用此模板:

<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>

然后我想在每个模板范围内选择class="content"的所有元素以便操作它们。 我怎样才能用JS实现这个目标?

编辑:

Plunker

在这个planker中,console.log应该两次打印“1”并且当模板第二次加载时打印“1”然后再打印“2”

2 个答案:

答案 0 :(得分:3)

经过更多解释后,这是一个有效的例子:

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

主要思想是创建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;
            }
          });
        }
  }]);

答案 1 :(得分:2)

大多数情况下,您不希望在Angularjs中执行DOM操作,而是使用控制器挂钩事件。如果你必须在AngularJS中进行DOM操作,你可以使用指令
Docs on Creating a Directive that Manipulates the DOM

然后,您可以使用link函数抓取指令元素的子元素

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

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