
AngularJS, Meet the MVC
- Published on Thursday, 27 March 2014 03:11
- Hits: 3944
Jquery is a javascript library, AngularJS is a MVC Javascript Framework (embedded in HTML).
So this is the second huge difference. AngularJS separates the:
- Model = The data structure as well as the data itself (your DB, XML data, JSOn Data, ...)
- View = Output layer (in this case HTML code), the Interface with the User.
- Controller = Message transfer layer between the Model and the View. The business Logic
As soon as you master your skills as AngularJS, you will find really useful this model. You can use totally different Views for two totally different devices for the same application.
Let's use the previous example, and reorganize the code a little bit so the MVC software pattern:
The View: index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>My HTML File</title> <link rel="stylesheet" href="/css/bootstrap.min.css"> <script src="/js/angular.min.js"></script> <script src="/js/controllerMatrix.js"></script> </head> <body ng-app="app" ng-controller="AppCtrl as app"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Smile!</th> <th>Name</th> <th>Character</th> </tr> </thead> <tbody> <tr ng-repeat="actor in app.actors"> <td>{{$index + 1}}</td> <td><img alt="{{actor.name}}" src="/{{actor.img}}"></td> <td>{{actor.name}}</td> <td>{{actor.character}}</td> </tr> </tbody> </table> </body> </html>
The Controller: controllerMatrix.js
var app = angular.module('app', []); app.controller('AppCtrl', function ($http) { var app=this; $http.get('./matrix.php') .success(function (data) {app.actors=data;}) });
The Model: matrix.php
<?php echo('[{"name":"Keanu Reeves", "img":"./img/NeoSm.jpg", "character":"Neo"}, {"name":"Laurence Fishburne", "img":"./img/MorpheusSm.jpg", "character":"Morpheus"}, {"name":"Carrie-Anne Moss", "img":"./img/TrinitySm.jpg", "character":"Trinity"}, {"name":"Hugo Weaving", "img":"./img/AgentSmithSm.jpg", "character":"Agent Smith"}, {"name":"Joe Pantoliano", "img":"./img/CypherSm.jpg", "character":"Cypher"}]'); ?>
Check the Code:
hmmm, now the code starts to look cleaner and we are adding style to the results. What's next??. Next thing is time for you to forget accessing the DOM!!, ..it seems not feasible but you will check how possible and cool it is. That will happen next week!!
Follow up this Mini Great Tutorial:
- AngularJS, Get in the Matrix
- AngularJS, Meet the MVC
- AngularJS, No more Dom Manipulation
- AngularJS, Build your App!!
- Animate your App!!