我用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就执行了
很抱歉之前提问时候,过于着急,没有将背景描述清楚,其实,是这样的,
我所用的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>
求解啦!!
1 step.controller 不是 function
2 controller 本身需要依赖注入 题主确定这样添加controller可以么.....