Angular+Requirejs-每个数据重复两次

Angular + Requirejs - each data is repeated twice?

本文关键字:两次 数据 Angular+Requirejs-      更新时间:2023-09-26

我在Requirejs下运行Angular,但我多次出现控制器类中的数据重复两次的情况。除非我从div中删除ng-app="myApp"。为什么?

welcomeController.js,

define(['app'], function (app) {
    app.controller('welcomeController', ['$scope', function($scope) { 
        //your minsafe controller 
        $scope.message = "Message from WelcomeController"; 
        console.log($scope.message); // it is repeated twice here.
    }]);
});

HTML,

<head>
    <link rel="stylesheet" href="style.css">
    <script data-main="scripts/main.js" src="scripts/vendors/requirejs/require.js"></script>
</head>
<body>
    <div ng-app="myApp">
        <div ng-controller="welcomeController">
            {{message}}
        </div>
    </div>
</body>

main.js,

require.config({
    //baseUrl: "",
    // alias libraries paths.  Must set 'angular'
    paths: {
        'domReady': 'vendors/requirejs-domready/domReady',
        'angular': 'vendors/angular/angular',
        'angular-route': 'vendors/angular-route/angular-route',
        'jquery': 'vendors/jquery/dist/jquery'
    },
    // Add angular modules that does not support AMD out of the box, put it in a shim
    shim: {
        'angular': {
            exports: 'angular'
        },
        'angular-route': {
            exports: 'angular'
        }
    }
});
define([
    'controllers/welcomeController',
    'bootstrap'
]);

bootstrap.js,

define([
    'require',
    'angular',
    'app'
], function (require, ng) {
    'use strict';
    require(['domReady!'], function (document) {
        ng.bootstrap(document, ['myApp']);
    });
});

app.js,

define([
    'angular'
], function (ng) {
    'use strict';
    //For single module retrun.
    return ng.module('myApp', []);
});

但在没有Requirejs的情况下,它在Angular上运行良好。我不需要从div中移除ng-app="myApp"。为什么?

    <head>
        <link rel="stylesheet" href="style.css">
        <script src="scripts/vendors/angular/angular.js"></script>
        <script>
            var myApp = angular.module('myApp',[]);
            myApp.controller('welcomeController', ['$scope', function($scope) {
                $scope.message = "Message from WelcomeController"; 
                console.log($scope.message); // It occurs only once.
            }]);
        </script>
    </head>
    <body>
        <div ng-app="myApp">
            <div ng-controller="welcomeController">
                {{message}}
            </div>
        </div>
    </body>

我在使用Angular的Requirejs下做错了什么?

您正在引导Angular两次:一次使用ng-app指令,一次使用bootstrap.js中的ng.bootstrap(...)代码!转到自动(ng-app)或手动(angular.bootstrap)引导。

此外,正如Josep在他(已删除)的回答中提到的那样,最好将angular-route填充为:

shim: {
    'angular-route': {
        deps: ['angular']
    }
}

这不是问题的原因,但将防止未来潜在的问题(即在Angular之前加载路由)。


angular require lazy可能包含一些有用的想法,用于angular RequireJS与lazy加载的集成