使用使用需求requirejs AngularJS路由和负载控制器 [英] Using AngularJS routing and loading controllers on demand using requirejs

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

问题描述

我想使用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文件被正确加载,但我看不到在渲染视图绑定值的数据。我不知道我是否可以指定控制器其他方式的价值,将等待异步调用(加载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

您需要在每条航线上定义resolve属性,并为其分配一个返回承诺的功能。该功能可以动态加载脚本包含目标控制器和解决的承诺,一旦加载完成。在此<一个href=\"http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx\"相对=nofollow>文章,丹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.

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

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