Naguib Ihab Naguib Ihab - 16 days ago 7
AngularJS Question

controller breaks the directive when in the same module

This is what I have in my js file:

//classRelationship.directive.js
'use strict';

angular.module('app.class',[]).directive('classRelationship', function(){
return {
restrict: 'E',
template: 'I AM HERE'
};
});

angular.module('app.class',[]).controller('classRelationshipCtrl', ['$scope', function($scope){
console.info('test');
}]);


And this is my html:

// main.html
<div class="panel panel-default">
<div class="panel-heading"><span class="glyphicon glyphicon-th"></span> Manage Students</div>
<div class="panel-body">
<class-relationship></class-relationship>
</div>

</div>


At this point the
I AM HERE
is not coming up in the html page, when I remove the controller or change the module the directive gets claled and i can see the template text in the html, i.e.

//classRelationship.directive.js
'use strict';

angular.module('app.class',[]).directive('classRelationship', function(){
return {
restrict: 'E',
template: 'I AM HERE'
};
});

angular.module('app.aNewModule',[]).controller('classRelationshipCtrl', ['$scope', function($scope){
console.info('test');
}]);


I am not getting any errors on the js console or any warnings and there's nothing else attached to that module
app.class
. Any idea why this is happening?

Answer

You're calling

angular.module('app.class',[])

twice.

That defines the module, and thus overwrites the previously defined module.

To get a reference to a previously defined module, you need to use the function without the second array parameter:

angular.module('app.class').controller(...