Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive loaded with RequireJS not compiling

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 is a partial that's loaded into ng-view

like image 258
iamsar Avatar asked Mar 22 '23 10:03

iamsar


1 Answers

Angular cannot load directives after it has been bootstrapped. My suggestion is:

  1. Make myDirective.js do a define(), not a require()
  2. Make sure myDirective.js is run before the require(['angular'],...) statement in config.js, e.g. do require(['angular','myDirective'],...). For this to work, myDirective should be shimmed to depend on angular - thanks @ David Grinberg.

As a sidenote, take a look at this in Stackoverflow/this in GitHub, we have been trying to do RequireJS + Angular play together.

like image 108
Nikos Paraskevopoulos Avatar answered Apr 10 '23 10:04

Nikos Paraskevopoulos