Angularjs 将控制器解析为字符串 [英] Angularjs resolve with controller as string

查看:22
本文介绍了Angularjs 将控制器解析为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写 angular 控制器的风格是这样的(使用控制器名称而不是函数)

My style of writing angular controllers is like this (using controller name instead of function)

angular.module('mymodule', [
])
    .controller('myController', [
        '$scope',
        function($scope) {
            // Some code here

        }
    ]);

我现在需要的是在提供我想要定义解析部分的路由时:

What I need now is when providing i routes I want to define resolve part:

 $routeProvider.when('/someroute', {
        templateUrl: 'partials/someroute.html', 
        resolve: myController.resolve}) // THIS IS THE CRITICAL LINE

既然控制器被定义为一个名字如何完成下面的解析部分?

Since controller is defined as a name how to accomplish resolve part bellow?

为了更详细地说明,我想在路由解析之前从服务器加载一些数据,然后在控制器中使用这些数据.

To clarify more in details I want to load some data from server before route is resolved and then use these data in controller.

更新: 更准确地说,我希望每个模块都有其解析"函数,该函数将在执行该控制器的 root 之前调用.这篇文章中的解决方案(由 Misko 回答Hevery) 完全符合我的要求,但我没有将控制器作为函数而是作为名称.

UPDATE: To be more precise I want each module has its "resolve" function that will be called before root with that controller is executed. Solution in this post (answered by Misko Hevery) does exactly what I want but I don't have controllers as functions but as a names.

推荐答案

控制器定义和解析部分将在路由定义中单独指定.

The controller definition and resolve parts are to be specified separately on the route definition.

如果您在模块级别定义控制器,则需要将它们作为字符串引用,因此:

If you define controllers on a module level you need to reference them as string, so:

 $routeProvider.when('/someroute', {
        templateUrl: 'partials/someroute.html', 
        controller: 'myController',
        resolve: {
          myVar: function(){
            //code to be executed before route change goes here
          };
        });

上面的代码还展示了如何定义一组将在路由更改之前解析的变量.当解析这些变量时,可以将这些变量注入控制器,因此以上面代码片段中的示例为例,您可以像这样编写控制器:

The above code also shows how to define a set of variables that will be resolved before route changes. When resolved those variables can be injected to a controller so taking the example from the snippet above you would write your controller like so:

.controller('myController', ['$scope', 'myVar', function($scope, myVar) {
            // myVar is already resolved and injected here
        }
    ]);

此视频也可能有所帮助:http://www.youtube.com/watch?v=P6KITGRQujQ

This video might help as well: http://www.youtube.com/watch?v=P6KITGRQujQ

这篇关于Angularjs 将控制器解析为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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