Reputation: 11642
In each tutorial focusing on the AngularJS I saw that all controllers was in one file controllers.js.
I think, that more practical is have to controllers in separated files.
Question is:
how can i create separated controllers in AngularJS? How to put controller CRUD methods inside the Controller (to have structure like this)?
Controller Users
- method get
- method add
- method edit
- method delete
Thanks for any help and example how to.
Upvotes: 2
Views: 74
Reputation: 4882
I suggest this approch (see example below)
Javascript:
// first file, must be include in first in your HTML
var example = angular.module('example', []);
example.factory('IndexModel', function() {
return {
get: function() {
return 'index controller';
}
};
});
example.controller('Index', function($scope, IndexModel) {
$scope.name = IndexModel.get();
});
// other file
var example = angular.module('example'); // angular module is accessible like this
example.factory('UserModel', function() {
return {
get: function() {
return 'user controller';
}
}
});
example.controller('User', function($scope, UserModel) {
$scope.name = UserModel.get();
});
Codepen: http://codepen.io/anon/pen/bAvEl
Upvotes: 1
Reputation: 47290
angular.module('controllers', []);
Add this on your angular app initialization code, then in each controller file just something like the following (and obvs reference the script file in html) :
(function() {
angular.module('controllers').controller('UserController', function($scope, $http) {
// your crud methods
$http.get('your-user-rest-url').success(function(result) {
return $scope.user = result;
});
});
}).call(this);
Upvotes: 0