Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS philosophy - controllers as "windows" to services

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!

like image 387
cemulate Avatar asked Jun 21 '13 05:06

cemulate


People also ask

What are the AngularJS controllers?

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.

Why are controllers used in AngularJS?

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.

What is the use of angular controllers in the application?

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.

Does angular use JavaScript?

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.


1 Answers

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).

like image 165
Mark Rajcok Avatar answered Oct 10 '22 02:10

Mark Rajcok