在AngularJS中,如何动态创建新的ngController?(In AngularJS how can I create a new ngController dynamically?)

编程入门 行业动态 更新时间:2024-10-03 14:26:21
在AngularJS中,如何动态创建新的ngController?(In AngularJS how can I create a new ngController dynamically?)

我正在尝试动态创建新的ngController ,这可能吗? 我没有用ngRepeat或其他东西将它写入模板,因为用户可能永远不会创建某个ngController的实例。

这是我当前模板的一个示例:

<div ng-controller="ViewUsers"> <div class="viewUsersList"> <table> <tr class="userRow" ng-click="viewUser(user.user_id)" ng-repeat="user in users"> <td>{{user.first_name}} {{user.last_name}} <br />{{user.phone}} </td> </tr> </table> </div> </div>

到目前为止它的效果很好。 当用户单击.userRow它会调用viewUser(ID) 。 问题出在这里:

我想创建一个新的代码块,如下所示:

<div ng-controller="UserDetail"> {{first_name}} </div>

并将其附加到DOM。

因此,如果他们点击Bobby和Sally ,两个UserDetail控制器对象将被添加到DOM并相应地工作。 (理想情况下,我想传递数据绑定的user模型,但这是为了以后)。

我在JSBin中尝试了一个贫民窟版本,但如果可能的话我宁愿不使用JQuery:

http://jsbin.com/EdOteTav/2/edit

任何人都可以对此有所启发吗? 提前致谢

I'm trying to create new ngControllers on the fly, is this possible? I'm not writing it into the template with a ngRepeat or anything, since the user might never create an instance of a certain ngController.

Here's an example of my current template:

<div ng-controller="ViewUsers"> <div class="viewUsersList"> <table> <tr class="userRow" ng-click="viewUser(user.user_id)" ng-repeat="user in users"> <td>{{user.first_name}} {{user.last_name}} <br />{{user.phone}} </td> </tr> </table> </div> </div>

So far it works great. When the user clicks a .userRow it calls viewUser(ID). The problem is here:

I want to create a new block of code like this:

<div ng-controller="UserDetail"> {{first_name}} </div>

And append this to the DOM.

So if they click on Bobby and Sally, two UserDetail controller objects would be added to the DOM and work accordingly. (Ideally, I'd like to pass in the data-bound user model, but that's for later).

I tried a ghetto version in JSBin, but I'd rather not use JQuery if possible:

http://jsbin.com/EdOteTav/2/edit

Can anyone shine some light on this? Thanks in advance

最满意答案

我会稍微改变代码并使用指令而不是控制器。 在jsfiddle中查看这个简单快速的示例。

该指令将处理单击事件并显示您想要在DOM上显示的任何内容。 您可以从指令中的scope.user获取完整的用户对象。

I would change the code little bit and use directive instead of controller. See this simple and quick example in jsfiddle.

The directive would handle the click events and display whatever you want to display on the DOM. You can get the full user object from scope.user inside the directive.

更多推荐

本文发布于:2023-07-09 10:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   AngularJS   ngController   dynamically   create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!