ng-repeat结合ng-controller问题

我用ng-repeat指令循环生成多个div,然后又想为每个div绑定不同的controller,设想如下

<div class="step"
  ng-repeat="step in steps">
  <div ng-controller="step.controller">
  </div>
</div>

但这样不行,会报错,因为step.controller还没来得及解析成对应的ctrl名,ng-controller就执行了

clipboard.png

很抱歉之前提问时候,过于着急,没有将背景描述清楚,其实,是这样的,
我所用的angularjs框架 controller是采用动态加载,也就是访问某个路由时,才动态加载所需ctrl(使用$controllerProvider实现)。
然后我最近在做个向导组件,就是有上一步、下一步、提交这样的交互。每一步的页面都是之前已经做好的模块,现在只不过是因为业务上的关系要将这几个模块串起来。
向导组件实现过程,我就想到了这样,如下

(重要的一步,也是我遇到的问题)

<div class="step"
  ng-repeat="step in steps">
  <div ng-controller="step.controller">
      <div ng-include="step.templateUrl"></div>
  </div>
</div>

思路是通过ng-repeat循环生成每一个步骤的页面,然后定义一个step数组,step里存放每一步的ctrl、templateUrl(模板路径)

var step = [
    {
       controller: 'you.good.boy as xyz',
       templateUrl: '/segmentfault.com/q/1010000009555726/edit.html' 
    },
    {
       controller: 'qqq.ww.eas as qwe',
       templateUrl: '/segmentfault.com/q/1010000009555726/qwe.html' 
    },
    {
       controller: 'gg.dd.zsz as gds',
       templateUrl: '/segmentfault.com/q/1010000009555726/gds.html' 
    }
];

每一步所用到的ctrl已经在访问该页面(路由)时提前加载完成,所以如果我这样写是可以的
(you.good.boy在访问该页面时 加载注册了)

<div ng-controller="you.good.boy">
    <div ng-include="'/segmentfault.com/q/1010000009555726/edit.html'"></div>
</div>

这样子,是可以正常拿到ctrl,并且通过ctrl解析edit.html文件

但是使用ng-repeat就不行,因为step.controller还没来得及解析成对应的值(也就是ctrl名)就被ng-controller拿去用了,然后就gg啦

<div class="step"
  ng-repeat="step in steps">
  <div ng-controller="step.controller">
  </div>
</div>

求解啦!!
clipboard.png

阅读 3.6k
4 个回答

1 step.controller 不是 function

2 controller 本身需要依赖注入 题主确定这样添加controller可以么.....

很有意思的写法,不过这样写是不行的。

controller在应该影响的是一个作用域,跟圈地保护一样,你只需要在当前的controller中对不同的step按照index的不同来区分操作

根据你的报错,原因 多半是你没有拿到其他 controller 的 reference(引用),只传进来了一个字符串。

只要你能在一个 controller 中获取到其他 controller 的 reference,那么你就可以这么玩儿:

$scope.controllers = [firstCtrl, secondCtrl, thirdCtrl];

然后 ng-repeat 里面遍历这个东西就行,这样你就能通过引用调用其他 controller 了

强行要实现不是不行。我能想到的方式就是通过 global function。在早期的 Angular 版本中,允许使用 global function 作为 controller。只要我们把它们都定义在全局作用域,那么 controller 之间就可以互相引用了,这很关键

就像这样:

var myApp = angular.module('myApp',[]);

function parentCtrl($scope) {
    $scope.controllers = [firstCtrl, secondCtrl, thirdCtrl];
}

function firstCtrl($scope){}

function secondCtrl($scope){}

function thirdCtrl($scope){}

只是印象中,应该是 1.3.x 之后,不允许这么玩儿了。

写了个 demo,参考下吧(只是我想不到这种写法有什么实际用途=。=
https://jsfiddle.net/S1ngS1ng...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题