Tuesday, October 18, 2016

Views, Controllers and Scope in Angular JS

The way it works in Angular is you have a View, which is what we’ve been doing in the previous section with our Directives, our Filters and our Data Binding.

But we don’t want to put all of our logic into the View because it’s not very maintainable or testable or all those types of things.

Instead we’re going to have a special little JavaScript object – a container - called a Controller. The Controller will drive things. It’s going to control ultimately what data gets bound into the View. If the View passes up data to the controller it will handle passing off maybe to a service which then  updates a back-end data store.

The glue between the View and the Controller is something called the Scope, and in Angular you’re going to see a lot of objects or variables that start with $. $scope represents the scope object.

When I say it’s the glue, it literally is the thing that ties the controller to the view.

You’ll see that the view can know about the controller because there’s a directive for that if you’d like to use it but the controller itself, to make it testable and a few things – loosely coupled and modular and all that good stuff – shouldn’t know anything about the view. In fact you should be able to define a controller that you can bind to different views. Maybe you have a mobile view, you have a desktop view or whatever it may be.

So the scope is this glue between them. Now for folks that have worked with Knockout or some of the different data binding frameworks out there, not just JavaScript but other desktop modes and things, you might have heard the term “ViewModel”.

A ViewModel literally is the model – the data – for the view. Well that’s really all the scope is. The scope is our ViewModel and it’s the glue between the view and the controller.

No comments:
Write comments
Recommended Posts × +