使用 RequireJS 加载的 AngularJS 指令未编译 [英] AngularJS directive loaded with RequireJS not compiling
问题描述
我正处于使用 AngularJS 和 RequireJS 构建大型应用程序的开始阶段.所有加载的东西都找到了,但指令并没有像他们应该的那样操作 DOM.没有错误报告并且应用程序的其余部分工作正常:视图已加载并且 $scope 是可绑定的.检查控制台显示所有文件已加载.我假设这是一个延迟加载问题,因为我的指令根本没有在正确的时间加载.我很感激有关如何在这方面正确加载指令的任何见解.除非它是 Angular 的 jqLite 的一部分,否则请不要建议使用 jQuery.
I'm in the beginning stages of building a large app with AngularJS and RequireJS. Everything loads find but directives aren't manipulating the DOM as they should. No errors are being reported and rest of the app works fine: Views are loaded and $scope is bindable. Examining the console shows that all the files loaded. I'm assuming this is a lazy load issue in that my directive is simply not loading at the correct time. I'd appreciate any insight into how to properly load directives in this regard. Unless it's a part of Angular's jqLite, please refrain from suggesting jQuery.
config.js
require.config({
paths: { angular: '../vendor/angular' }
shim: { angular: { exports: 'angular' } }
});
require(['angular'], function(angular) {
angular.bootstrap(document, ['myApp']);
});
myApp.js
define(['angular', 'angular-resource'], function (angular) {
return angular.module('myApp', ['ngResource']);
});
routing.js
define(['myApp', 'controllers/mainCtrl'], function (myApp) {
return myApp.config(['$routeProvider', function($routeProvider) {
...
}]);
});
mainCtrl.js
define(['myApp', 'directives/myDirective'], function (myApp) {
return myApp.controller('mainCtrl', ['$scope', function ($scope) {
...
}]);
});
myDirective.js
require(['myApp'], function (myApp) {
myApp.directive('superman', [function() {
return {
restrict: 'C',
template: '<div>Here I am to save the day</div>'
}
}])
});
home.html
<div class="superman">This should be replaced</div>
home.html 是加载到 ng-view 中的部分
推荐答案
Angular 在引导后无法加载指令.我的建议是:
Angular cannot load directives after it has been bootstrapped. My suggestion is:
- 让
myDirective.js
做一个define()
,而不是一个require()
- 确保
myDirective.js
在 config.js 中的require(['angular'],...)
语句之前运行,例如做require(['angular','myDirective'],...)
.为了使其工作,myDirective
应该被填充以依赖于angular
- 感谢 @ David Grinberg.
- Make
myDirective.js
do adefine()
, not arequire()
- Make sure
myDirective.js
is run before therequire(['angular'],...)
statement in config.js, e.g. dorequire(['angular','myDirective'],...)
. For this to work,myDirective
should be shimmed to depend onangular
- thanks @ David Grinberg.
作为旁注,看看Stackoverflow中的这个/<一个 href="https://github.com/nikospara/angular-require-lazy" rel="nofollow noreferrer">这个在 GitHub 上,我们一直在尝试做 RequireJS + Angular 一起玩.
As a sidenote, take a look at this in Stackoverflow/this in GitHub, we have been trying to do RequireJS + Angular play together.
这篇关于使用 RequireJS 加载的 AngularJS 指令未编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!