加载了RequireJS的AngularJS指令未编译

iam*_*sar 4 requirejs angularjs angularjs-directive

我正处于使用AngularJS和RequireJS构建大型应用程序的初级阶段.一切都加载了,但是指令并没有按照它们的方式操纵DOM.没有报告错误,应用程序的其余部分工作正常:视图已加载且$ scope可绑定.检查控制台显示已加载所有文件.我假设这是一个懒惰的加载问题,因为我的指令根本没有在正确的时间加载.我很感激有关如何在这方面正确加载指令的任何见解.除非它是Angular的jqLit​​e的一部分,否则请不要建议使用jQuery.

config.js

require.config({
  paths: { angular: '../vendor/angular' }
  shim: { angular: { exports: 'angular' } }
});
require(['angular'], function(angular) {
  angular.bootstrap(document, ['myApp']);
});
Run Code Online (Sandbox Code Playgroud)

myApp.js

define(['angular', 'angular-resource'], function (angular) {
  return angular.module('myApp', ['ngResource']);
});
Run Code Online (Sandbox Code Playgroud)

routing.js

define(['myApp', 'controllers/mainCtrl'], function (myApp) {
  return myApp.config(['$routeProvider', function($routeProvider) {
    ...
  }]);
});
Run Code Online (Sandbox Code Playgroud)

mainCtrl.js

define(['myApp', 'directives/myDirective'], function (myApp) {
  return myApp.controller('mainCtrl', ['$scope', function ($scope) {
    ...
  }]);
});
Run Code Online (Sandbox Code Playgroud)

myDirective.js

require(['myApp'], function (myApp) {
  myApp.directive('superman', [function() {
    return {
      restrict: 'C',
      template: '<div>Here I am to save the day</div>'
    }
  }])
});
Run Code Online (Sandbox Code Playgroud)

home.html的

<div class="superman">This should be replaced</div>
Run Code Online (Sandbox Code Playgroud)

home.html是加载到ng-view中的部分内容

Nik*_*los 7

Angular在引导后无法加载指令.我的建议是:

  1. myDirective.jsdefine(),而不是require()
  2. 确保在config.js中myDirective.jsrequire(['angular'],...)语句之前运行,例如do require(['angular','myDirective'],...).为了这个工作,myDirective应该采取调整依赖angular- 感谢@ David Grinberg.

作为旁注,请看看Stackoverflow/这在GitHub 中的这个,我们一直在尝试将RequireJS + Angular一起玩.