使用 AngularJS 路由并使用 requirejs 按需加载控制器 [英] Using AngularJS routing and loading controllers on demand using requirejs

查看:13
本文介绍了使用 AngularJS 路由并使用 requirejs 按需加载控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试结合使用 AngularJS 和 RequireJS.我想使用 $routeProvider 服务并避免在应用程序启动时为我的视图加载所有控制器.为此,我尝试了以下方法:

I'm trying to use AngularJS and RequireJS in combination. I would like to use the $routeProvider service and avoid having to load all the controllers for my views on application startup. For that, I tried the following:

define(['require', 'angular', 'appModule'], function (require, angular, app) {
    app.config(['$routeProvider', function($routeProvider) {
      $routeProvider
          .when('/sites', {templateUrl: '/Site/GetSitesView', controller: function() {
            require(['sitesController'], function(SitesController) {
                return new SitesController();
            })
        }})
    }]);
});

不幸的是,这对我不起作用.没有错误.包含控制器的 JS 文件正在正确加载,但我在渲染视图中看不到数据绑定值.我想知道是否可以通过其他方式分配 controller 的值,等待异步调用(加载 JS 文件)完成.

Unfortunately, that did not work for me. There are no errors. The JS file containing the controller is being loaded properly but I cannot see the data bound value in the rendered view. I was wondering whether I could assign the value of controller in some other way that would wait for the asynchronous call (to load the JS file) to complete.

有什么想法吗?

推荐答案

你可以找到解决方案这里

You can find the solution here

您需要在每个路由上定义一个解析属性,并为其分配一个返回承诺的函数.该函数可以动态加载包含目标控制器的脚本,并在加载完成后解析promise.在这个 文章Dan Wahlin展示了如何使用约定优于配置来获得更实用的路由.

You need to define a resolve property on each route and assign it a function that returns a promise. The function can dynamically load the script contains the target controller and resolve the promise once the loading is complete. In this article, Dan Wahlin shows how to use convention over configuration to have more practical routing.

这篇关于使用 AngularJS 路由并使用 requirejs 按需加载控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆