简体   繁体   English

如何访问 ng-repeat 中的控制器变量?

[英]How can I access a controller variable inside ng-repeat?

I need to access variable from ng-repeat inside controller, which is inside ng-repeat, code provided below.我需要从控制器内部的 ng-repeat 访问变量,该控制器位于 ng- ng-repeat内部,代码如下。 Unfortunately it won't work for me.不幸的是,它对我不起作用。

<div ng-controller="ParentCtrl">
    <div ng-repeat="r in results">
        <div ng-controller="SomeCtrl">
            <p>{{r.something}}</p>   ($parent.r.something won't work either)
        </div>
    </div>
</div>

The thing I need is to make ng-repeat within one controller, to make list of available desks (in parent controller I have searching, filters etc.) and then, when I click the button in chosen row of list (results), I need to take its (row's) parameters and do something with them INSIDE second (child?) controller.我需要做的是在一个控制器中进行 ng-repeat,列出可用的办公桌(在父控制器中我有搜索、过滤器等),然后,当我单击所选列表行(结果)中的按钮时,我需要获取它的(行的)参数并在第二个(孩子?)控制器中对它们做一些事情。

Is it possible?可能吗? And if possible - how to do it?如果可能的话 - 怎么做?

Use the ng-repeat variable ($index) in the html and call a function on the controller在 html 中使用 ng-repeat 变量 ($index) 并调用控制器上的函数

<div ng-repeat="r in results">
    <div ng-controller="SomeCtrl">
        <p>{{r.doSomething($index)}}</p> 
    </div>
</div>

ng-repeat should be nested in the ng-controller if you want to access variables in ng-controller.如果你想访问 ng-controller 中的变量,ng-repeat 应该嵌套在 ng-controller 中。 Lets assume you have "results" defined as an object in SomeCtrl, you will be able to access it with an ng-repeat.假设您将“结果”定义为 SomeCtrl 中的对象,您将能够使用 ng-repeat 访问它。 Example:例子:

In your controllers.js在你的 controllers.js

appControllers.controller('SomeCtrl', function(){
      $scope.results = someData;
});

In your view,在你看来,

<div ng-controller="SomeCtrl">
   <div ng-repeat="r in results">
      <p>{{r.property}}</p>
   </div>
</div>

Another solution would be to use the controller as syntax.另一种解决方案是将控制器用作语法。 See plunker for details.有关详细信息,请参阅plunker

<div ng-controller="ParentCtrl as parent">
    <div ng-repeat="r in parent.results">
        <div ng-controller="SomeCtrl as child">
            <p>{{child.something(r)}}</p>
        </div>
    </div>
</div> 

The recommended way to communicate across controller is via services.推荐的跨控制器通信方式是通过服务。 But in your case, I am not sure whether creating a cross cutting service would solve anything.. It would be something to think about though但是在你的情况下,我不确定创建一个横切服务是否能解决任何问题。虽然这将是一些需要考虑的事情

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

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