简体   繁体   English

如何在页面上多次使用同一控制器和同一视图

[英]How to use the same controller and same view multiple times on a page

I am trying to make a single page app where I want to load screens (partial views) via ajax. 我正在尝试制作一个单页面应用程序,我想在其中通过ajax加载屏幕(局部视图)。 The problem is that the user want's to open the same screen multiple times (in tabs). 问题是用户希望多次打开同一屏幕(在选项卡中)。 I tried to load the controller code on initial load and loaded my screens (partial views) via AJAX. 我尝试在初始加载时加载控制器代码,并通过AJAX加载了屏幕(局部视图)。 But the controller is already executed by the time the screen (partial view) is loaded. 但是在加载屏幕(部分视图)时,控制器已经执行。

I want to know how to make controller run after the partial view is loaded? 我想知道如何在部分视图加载后使控制器运行吗?

Or better yet, how to tackle this situation where i want to load the same view multiple time with different data/state? 还是更好,如何解决这种情况,即我想多次使用不同的数据/状态加载同一视图?

I found a solution to the problem I was facing. 我找到了解决所面临问题的方法。 I am not sure if it is the best way to move forward but given the limited knowledge I have on AngularJS so far, this solution is my best bet. 我不确定这是否是前进的最佳方法,但是鉴于到目前为止我对AngularJS的了解有限,所以这种解决方案是我最好的选择。 If anyone can come up with a better solution, I am all ears. 如果有人能提出更好的解决方案,我全神贯注。

Instead of registering controller up front, I am registering the controller when the view is requested. 我不是在先注册控制器,而是在请求视图时注册控制器。

Also, I am appending a new div to the container where I want the view to appear. 另外,我要将新的div附加到要显示视图的容器中。 There is some jQuery on the page that hides other views and only shows the current view. 页面上有一些jQuery,可隐藏其他视图,仅显示当前视图。

Step 1 第1步

Assigned $controllerProvider.register to a variable on App Scope $controllerProvider.register分配给App Scope上的变量

var myApp = angular.module("myApp", []);
angular.module("myApp").config(function ($controllerProvider) {
                   myApp.registerCtrl = $controllerProvider.register;
               });

Step 2 第2步

In the function where I have to load the view dynamically, I did the following 在必须动态加载视图的函数中,我执行了以下操作

$("#viewContainer").append($compile('<div ng-include="pageUrl"></div>')($scope));

The above line adds a div with ng-include directive. 上一行添加了带有ng-include指令的div。 It also compiles the directive. 它还会编译指令。 The pageUrl is where I am keeping the url to the view I want to include. pageUrl是我将URL保留到要包含的视图的位置。

Step 3 第三步

In the view file I have to load, I have include JavaScript file that holds my controller. 在我必须加载的视图文件中,我包含了包含控制器的JavaScript文件。 The rest of the file contains simple HTML with directives. 文件的其余部分包含带有指令的简单HTML。 In the JS file, instead of creating the controller, I am registering the controller like 在JS文件中,我没有像创建控制器那样注册控制器

angular.module('myApp').registerCtrl("MyController", MyController);

I hope this is helpful to others. 我希望这对其他人有帮助。

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

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