AngularJS with RequireJS, manual initialisation, d

2019-07-25 11:08发布

问题:

In the following example why does AngularJS compile {{'world'}} in my HTML but not act upon the directive?

HTML

<body>
    <div>Hello {{'World'}}!</div>
    <example>should be replaced</example>
    <script data-main="lib/main" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.5/require.min.js"></script>
</body>

main.js

require.config({
    paths: {
        jquery: '//code.jquery.com/jquery-1.10.0.min',
        angular: '//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min'
    },
    shim: {
        'angular' : {'exports' : 'angular'}
    },
    priority: [
        "angular"
    ]
});

require( [
    'jquery',
    'angular',
    'app'
    ], function($, angular, app) {
        'use strict';
        $(document).ready(function () {
            angular.bootstrap(document,[]);
            app.directive('example',function(){
            return {
                restrict: "E",
                template:"<div>Replaced</div>"
            }
        })
    });
});

app.js

define([
    'angular'
], function (angular) {
    'use strict';
    return angular.module('myApp', []);
});

Visible in browser window when run

Hello World!
should be replaced

So Angular has initialised as {{'World'}} has compiled to World but the 'example' directive has failed as 'should be replaced' hasn't been replaced with 'Replaced'

I realise there is no app holder in the HTML but if I try to add one I get an error

For example

<div ng-app='myApp'>
    <div>Hello {{'World'}}!</div>
    <example>should be replaced</example>
</div>

Gives error

Uncaught Error: No module: myApp    http:// ...

回答1:

Because you're late/lazy loading all of the modules (using AMD) you need to manually bootstrap your application after the load is complete. Take a look at the manual initialization section of http://docs.angularjs.org/guide/bootstrap for an example of doing this.

Make sure the bootstrap is not called until angular document is ready. Also include the app you want bootstrapped at that point as a module dependency for the bootstrap call (e.g. angular.bootstrap(document, ['myapp']);).