我在Requirejs下运行Angular,但我有多次出现,其中控制器类中的数据重复两次。除非我从ng-app="myApp"
中移除div
。为什么呢?
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上它可以正常工作。我不需要从ng-app="myApp"
删除div
。为什么呢?
<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下我做错了什么?
答案 0 :(得分:0)
你正在引导Angular两次:一次使用ng-app
指令,一次使用bootstrap.js中的ng.bootstrap(...)
代码!去自动(ng-app
)或手动(angular.bootstrap
)自举。
另外,就像Josep在他的(已删除)答案中提到的那样,最好将angular-route
改为:{/ p>
shim: {
'angular-route': {
deps: ['angular']
}
}
这是 NOT 问题的原因,但会阻止潜在的未来问题(即在Angular之前加载路由)。
angular-require-lazy可能包含Angular-RequireJS与延迟加载
集成的一些有用的想法