Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - AngularJS: dynamically assign controller from ng-repeat

I'm trying to dynamically assign a controller for included template like so:

<section ng-repeat="panel in panels">
    <div ng-include="'path/to/file.html'" ng-controller="{{panel}}"></div>
</section>

But Angular complains that {{panel}} is undefined.

I'm guessing that {{panel}} isn't defined yet (because I can echo out {{panel}} inside the template).

I've seen plenty of examples of people setting ng-controller equal to a variable like so: ng-controller="template.ctrlr". But, without creating a duplicate concurrant loop, I can't figure out how to have the value of {{panel}} available when ng-controller needs it.

P.S. I also tried setting ng-controller="{{panel}}" in my template (thinking it must have resolved by then), but no dice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that ng-controller should point to controller itself, not just string with controller's name.

So you might want to define $scope.sidepanels as array with pointers to controllers, something like this, maybe:

$scope.sidepanels = [Alerts, Subscriptions];

Here is the working example on js fiddle http://jsfiddle.net/ADukg/1559/

However, i find very weird all this situation when you might want to set up controllers in ngRepeat.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...