简体   繁体   English

角。 如何获得ng-repeat项目范围

[英]Angular. How to get access of ng-repeat item scope

Code: 码:

<div ng-controller="someCtrl">
  <span ng-repeat="item in [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5}]"></span>
</div>

Javascript: 使用Javascript:

.controller('someCtrl', function($scope){
  //how to get access to child scope of element with id===3?
  for(var i = 0,len = $('span').length;i<len;i++){
    if($('span').eq(i).scope().id === 3){
      //do something with scope of element with id===3
    }
  }
})

How to access this scope without DOM manipulations? 如何在没有DOM操作的情况下访问此范围?

Define the array in the controller. 在控制器中定义数组。 And then you can acces is easily: 然后您可以轻松访问:

<div ng-controller="someCtrl">
  <span ng-repeat="item in MyList"></span>
</div>

.controller('someCtrl', function($scope){
  $scope.MyList =  [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5}]

  $scope.Mylist[2]...
})

What you're trying to do, you can easily get to by doing it inside of the repeater. 您想要执行的操作,可以在中继器内部轻松完成。

<div ng-controller="someCtrl">
    <span ng-repeat="item in [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5}]">

        <!-- do whatever you want -->

        <!-- do something specific if it's id === 3 -->
        <span ng-if="item.id === 3">
            <strong>{{ item.id }}</strong> 
        </span> 
    </span>
</div>

Also, you never do DOM manipulation (Javascript / jQuery / whatever) inside of a controller / service / factory. 另外,您永远都不会在控制器/服务/工厂内部进行DOM操作(Javascript / jQuery /其他)。 Only inside directives , even though try to keep it minimal. 仅内部指令 ,即使尝试使其保持最小。

Disclamer: don't use this code in real applications! Disclamer:请勿在实际应用中使用此代码!

Okay this is terrible thing to do, but for the sake of academic interest I'm going to post the answer of how you can get hold of child scope from controller. 好的,这是一件可怕的事情,但是出于学术兴趣,我将发布关于如何从控制器获取子范围的答案。

Since ngRepeat creates child scopes of the current $scope for every rendered item, all you need to do is read $$childHead ( $first item) and from there check $$nextSibling scopes until you find necessary scope object. 由于ngRepeat为每个呈现的项目创建当前$scope子范围,因此您所需要做的就是读取$$childHead$first项目),然后从其中检查$$nextSibling范围,直到找到必要的范围对象。

One caveat: you need to run object search during next digest cycle, since there is nothing rendered yet during the digest controller is executed in. So you can use $timeout service for this: 一个警告:您需要在下一个摘要循环中运行对象搜索,因为在执行摘要控制器期间还没有呈现任何内容。因此,您可以使用$timeout服务:

$timeout(function() {
    var childScope = $scope.$$childHead;

    while (childScope = childScope.$$nextSibling) {
        if (childScope.item.id === 3) {
            break;
        }
    }

    console.log(childScope);
    alert(JSON.stringify(childScope.item));
});

Demo: http://plnkr.co/edit/KLtTSnrS8lIEejMhKuby?p=preview 演示: http //plnkr.co/edit/KLtTSnrS8lIEejMhKuby?p = preview

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

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