简体   繁体   English

运行angular.js作为回调(例如$ .ajax)

[英]Run angular.js as a callback ($.ajax, for example)

I'm writing an app with mostly two javascripts, resources_loader.js and app.js, where the first loads some json files used by app.js. 我正在编写一个主要包含两个javascripts的应用程序,resources_loader.js和app.js,其中第一个加载了app.js使用的一些json文件。

The problem is: app.js (which has angular.js stuff) should run only after resources_loader.js. 问题是:app.js(包含angular.js内容)应仅在resources_loader.js之后运行。 I tried to run angular code inside the success callback (resources_loader contains a deferred), but this not seems to work well. 我试图在成功回调中运行有角度的代码(resources_loader包含一个延迟的),但这似乎不能很好地工作。 Here's my index.html: 这是我的index.html:

<!doctype html>
<html ng-app="myapp">
<body>
    <script src="angular.js"></script>
    <script src="resources_loader.js"></script>
</body>
</html>

Consider that I moved app.js to resources_loader, inside the success callback. 考虑将我将app.js移至成功回调中的resources_loader。 Everytime I try to run it, angular raises the following exception: Uncaught Error: No module: myapp . 每当我尝试运行它时,angular都会引发以下异常: Uncaught Error: No module: myapp

My guess is that angular.module('myapp', []) should run before onload's event, which is not the case here. 我的猜测是angular.module('myapp', [])应该在onload事件之前运行,在这里情况并非如此。

Another thing is that I want to use yepnope.js in my project like this: 另一件事是我想像这样在我的项目中使用yepnope.js:

<script "yepnope.js"></script>
<script "resources_loader.js"></script>
<script>
    var loader = load_stuff();
    yepnope({
        test: loader.resolved(),
        yep: ['angular.js', 'app.js', 'foo.js', 'bar.js'],
        nope: ['fail.js']
    });
</script>

app.js contains angular code. app.js包含角度代码。 I think it's more performant because it only loads angular if the resources are loaded. 我认为它的性能更高,因为仅在加载资源时才加载角度。 But how can I do it? 但是我该怎么办呢?

Remove ng-app from <html> tag and use angular.bootstrap(document, ['myapp']); <html>标记中删除ng-app并使用angular.bootstrap(document, ['myapp']); to fire it up once your resources are loaded, like this: 在资源加载后启动它,如下所示:

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider', function($router, $location) {
    $location.html5Mode(true);

    $router
    .when('/', {
        templateUrl: 'some_template.html',
        controller: 'myController'
    });
}]);

// and then, after everything, run
angular.bootstrap(document, ['myapp']);

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

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