Reputation:
There is something I don't fully understand with AngularJS. If I declare the controllers this way:
angular.module('ngApp', []).controller('AboutCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
angular.module('ngApp', []).controller('ContactCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
angular.module('ngApp', []).controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
...whenever I try to test them only one of them pass the test case(s):
describe('MainCtrl', function () {
var scope;
beforeEach(module('ngApp'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
$controller('MainCtrl', { $scope: scope });
}));
it('should attach a list of `awesomeThings` to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
(I have also three files with the same test case repeated, the only thing that changes is the controller name: AboutCtrl
and ContactCtrl
in the apprpriate locations).
On the other hand, if I say: var app = angular.module('ngApp', []);
and then "attach" the controllers to it, everything works fine. The same if I attached them to the same chain in one angular.module('ngApp', []).controller(/* ... */).controller(/* ... */);
The reason I want them separate is because I want to have them in (three...N) different files.
Anyone has any clue?
Upvotes: 0
Views: 39
Reputation: 42736
By calling angular.module('ngApp', [])
you are creating a new module, not reusing the same one. In order to do that just call .module
with the app name and no other argument
angular.module('ngApp')
file1.js
angular.module('ngApp').controller(...);
file2.js
angular.module('ngApp').controller(...);
you could also just save the module to a global variable and just use that variable
main.js
var app = angular.module('ngApp',[]);
file1.js
app.controller(...);
file2.js
app.controller(...);
Upvotes: 0
Reputation: 22323
You are re-declaring your ngApp
module each time, rather than getting the already declared module.
From John Papa's Angular Style Guide:
•Only set once and get for all other instances.
Why?: A module should only be created once, then retrieved from that point and after.
/* recommended */ // to set a module angular.module('app', []); // to get a module angular.module('app');
Upvotes: 0