Sorry for the vague title;
I've been restructuring some of my AngularJS code, trying to be more "Angular" about it, and I've noticed this pattern popping up quite a bit:
app.service("someService", function(...) {
...
}
app.controller("ControllerForThisSection", function($scope, someService) {
$scope.someService = someService
}
Basically, the controller is mostly there to give the scope a reference to the service so a view can use it, like
<div ng-if="someService.status">
....
</div>
So I have more than a few controllers that do nothing more than depend on certain shared data or services and serve to make references to those services available through the scope.
Is there any disadvantage to using this design? Can I improve my thinking any? Is this the "angular" way to do it?
Thanks for any advice!
AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.
AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
Angular is an open-source front-end framework developed by Google for creating dynamic modern web apps. It uses JavaScript-based TypeScript programming language to eliminate dispensable code and ensure lighter and faster apps.
This is the "angular way". Shared data should be placed into services, then injected where needed.
I like to think of my Angular apps mainly in terms of models (which are usually stored in services) and views. The controllers are just the glue that allows us to project/extract the parts of our models that a particular UI view needs.
Also, think of services as returning a model API, not a model object (to quote Josh).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With