Angular + Requirejs - 每个数据重复两次?
我在Requirejs下运行Angular,但是我有这种多次出现,其中控制器类中的数据重复两次。除非我从div
删除ng-app="myApp"
。为什么?Angular + Requirejs - 每个数据重复两次?
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,
但在角工作正常无Requirejs。我不需要从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>
在Requirejs和Angular下我做了什么错误?
回答:
您正在引导两次Angular:一次使用ng-app
指令,一次使用bootstrap.js中的ng.bootstrap(...)
代码!去自动(ng-app
)或手动(angular.bootstrap
)自举。
此外,像何塞普在他(删除)答复中提到,最好是垫片angular-route
为:
shim: { 'angular-route': {
deps: ['angular']
}
}
这是不问题的原因,但会防止未来可能出现的问题(即在Angular之前加载的路线)。
angular-require-lazy可能包含角RequireJS整合一些有益的思路与延迟加载
以上是 Angular + Requirejs - 每个数据重复两次? 的全部内容, 来源链接: utcz.com/qa/259481.html