MVC In Angular
Definition Recap
-
Model: How we model our data in the code
-
View: What the user sees
- Controller: How the model and the view communicate
Model, in Angular
-
The model still represents the state of the program and the important data.
-
Angular lets us model data in plain old JSON objects
- Angular GIVES us "Services" and "Factories" which are helpful data modeling tools
Model, in Angular
-
Persistence has to be managed through AJAX, since we're trying to avoid nasty "page loads".
- All model code in Angular is client side JS code, but there may be a corresponding database model. Probably exposed by an API.
View, in Angular
- The view, in Angular, is still represented by HTML.
- Custom directives, and a special templating syntax are used.
- Render data: {{ exaluatedJavaScript }}
-
2-Way data binding:
<input ng-model="variableName" >
Controller, in Angular
-
Built with a specific Angular component, called a "controller"
-
Behavior is defined in JavaScript
-
Views must declare their controller in HTML using a custom attribute
Controller, in Angular
// JavaScript Controller Definition
// Application name, followed by an array of dependencies
// dependencies are similar to 'require' statements
var application = angular.module("myapp", [])
// Register a controller on our application
// Name, followed by the code for instantiating the controller
application.controller("HelloController", function($scope) {
// $scope is VERY special. We'll get to that.
$scope.hello = {};
$scope.hello.title = "World";
});
Controller, in Angular
<!-- Declare the application that this view belongs to -->
<html ng-app="myapp">
<head>
<meta charset="utf-8">
<title>Hello, World!</title>
</head>
<body>
<!-- declare the controller this div (and it's children) belongs to -->
<div ng-controller="HelloController">
<!-- hello.title here, is tied to $scope.hello.title -->
<h2>Hello, {{hello.title}}!</h2>
</div>
</body>
</html>
$scope: "View Model"
-
All communication between the view and the controller is managed by the $scope variable.
-
If you want something to be used by the view, you have to put it on the "view model", which in Angular is the $scope variable.
A Mental Model
View
HTML
Controller
JS, specifically constructed in a
.controller function
$scope
User input flows from
the view to the ctrl
Data from the program flows from the ctrl to the view
Questions?
MVC / MVVM / MVW in Angular
By Tyler Bettilyon
MVC / MVVM / MVW in Angular
- 1,819