Model-View-Controller Pattern in Web Development

a javascript framework n.w
1 / 33
Embed
Share

Explore the Model-View-Controller pattern in web development, AngularJS's role in solving common problems, and how HTML/jQuery mix Controller and View elements. Dive into implementation details and code structure to grasp key concepts.

  • Web Development
  • MVC Pattern
  • AngularJS
  • HTML
  • jQuery

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. A JavaScript framework SE-2840 Dr. Mark L. Hornick 1

  2. Review What is the Model-View-Controller pattern about? SE-2840 Dr. Mark L. Hornick 2

  3. What is AngularJS and what problem(s) does it address? First, consider the structure of the web apps you have done so far: Does the code present a clean implementation of the MVC pattern? Where is the View implemented? what code file(s)/module(s) create or modifie what is seen in the browser? Where is the Controller implemented? what code is responsible for getting data and deciding what data is to be displayed? Where is the Model implemented? what code is responsible for storing data? 3

  4. HTML/jQuery approach mixes Controller and View The typical paradigm is as follows: Access a DOM element Read its value Send the value to the Model OR Read a value from the Model Access a DOM element Update its content with the value SE-2840 Dr. Mark L. Hornick 4

  5. Typical jQuery approach <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>jQuery approach</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> // Note: this should be in a separate js file, but is here for simplicity of illustration. class JQApproach { constructor() { var self = this; $().ready(function () { self.onLoad(); }); } // onLoad handling is usually used to perform initialization onLoad() { let items = []; // initialize an empty array // When the button is pressed, append the value in the text box to the items array, // and then update the <ul> that displays all the <li> entries. $('#add').click(function () { let entry = $('#item').val(); // get value from button items.push(entry); // ...and add it to the items array displayList(); // tell the display to show the updated list }); Blue=UI manipulation in control code // This inner function iterates through the items array, // creating an <li> element in the <ul> list for each entry in the array. function displayList() { var index = 0; $('#list').html(""); // clear the <ul> list (note: managing the ui here) for( index in items ) { let entry = items[index]; $('#list').append('<li>Entry ' + index + ' is ' + entry + '</li>'); // note html mixed with script (ui+control) } } // end displayList } // end onLoad } // end JQApproach new JQApproach(); </script> </head> Green = UI markup <body> <p>A list of items</p> Add item:<input id='item' type='text' value="pen"/> <br> <button id='add'>Add</button> <ul id="list"> <!-- <li> items go here --> </ul> SE-2840 Dr. Mark L. Hornick 5 </body> </html>

  6. Low cohesion! High coupling! Bad code smell! Note that the JavaScript function knows about the View, since it explicitly has to add a <li> element to the <ul> This is an example of poor cohesion and tight coupling SE-2840 Dr. Mark L. Hornick 6

  7. AngularJS Motivation Evolution has moved wep app architecture towards SPA (single page applications) , where the : Server implements the Model (e.g. Phonebook) Client (browser) implements the View and Controller The Controller is responsible for Getting data from the server and making it accessible to the view. Extracting data from the view and posting it to the server The View is responsible for Deciding how to display information to ensure a unified UI experience (desktop, tablets, phones) SE-2840 Dr. Mark L. Hornick 7

  8. AngularJS is one of many competing frameworks that attempt/promise to: Decouple DOM manipulation from app logic (control) Decouple client-side from server-side Improve testability Make common coding tasks easier This is changing rapidly. To get the latest, google javascript mvc frameworks SE-2840 Dr. Mark L. Hornick 8

  9. One surveys results: Google: angularjs vs other frameworks for many differing opinions SE-2840 Dr. Mark L. Hornick 9

  10. AngularJS Eliminates need to manipulate DOM programmatically Uses a declarative approach to describe how the View should change as the app changes state (ie as data changes) Eliminates marshalling of data to and from the View AngularJS handles marshalling between the view and the controller SE-2840 Dr. Mark L. Hornick 10

  11. AngularJS is notfor everything Not a good fit for applications that require intensive and tricky DOM manipulation of the DOM (ie games, gui editors) In such cases, it is better to use a library that exposes a lower level of abstraction, like jQuery AngularJS is best-suited for CRUD (Create, Replace, Update, Delete) applications i.e. the majority of web applications SE-2840 Dr. Mark L. Hornick 11

  12. AngularJS Executive Summary Backed by Google Current stable release is 1.6.x Angular 2.x announced 9/2014 Angular 2.x released to beta 12/2015 Angular 2.0 released 9/15/2016 Angular 3.0 beta d but never released Angular 4.0 released 3/2017 Angular 5.0 released 11/2017 AngularJS allows you to decorate your HTML with special markup that synchronizes with your JavaScript leaving you to write your application logic instead of manually updating views. See https://www.madewithangular.com SE-2840 Dr. Mark L. Hornick 12

  13. Introductory topics Templates Expressions Directives Modules Controllers Scopes Data binding SE-2840 Dr. Mark L. Hornick 13

  14. AngularJS approach Templates are html files with Angular-specific elements. The Template accesses the model and functions from the controller to render the dynamic view of the data. <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Angular approach</title> Green: model and expression bindings used to access the model <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head> Blue: control code (we could implement this in a separate js file). AngularJS supplies a basic Controller implementation. <body ng-app="" ng-init="items=[]"> <p>A list of items:</p> Add item:<input ng-model='entry' type='text' ng-init="entry ='pen'"/> <br><button ng-click="items.push(entry)">Add</button> Red: AngularJS directives <ul> <li ng-repeat='entry in items track by $index'>{{entry}}</li> </ul> </body> </html> SE-2840 Dr. Mark L. Hornick 14

  15. Directives * ** *We can also omit the ng-init and instead initialize our data in a js file to keep Javascript out of our html ** The double-curly brace {{ }} syntax is almost always used instead of ng-bind 15

  16. Note on directive syntax Prior to HTML5, programmers relied on using 'class' or 'rel' attributes to store small bits of data that could be used in websites. This sometimes led to problems and could cause conflicts between the styling and functionality of websites. The advent of HTML5 introduced a new attribute known as 'data'. See http://www.w3schools.com/tags/att_global_data.asp SE-2840 Dr. Mark L. Hornick 16

  17. Data binding Q: Which Design Pattern is being used here within AngularJS? Note use of {{ }} Data binding is implemented within the Controller supplied by AngularJS SE-2840 Dr. Mark L. Hornick 17

  18. Data binding demo SE-2840 Dr. Mark L. Hornick 18

  19. The ng-click directive This is Angular s substitute for the HTML onclickattribute (and jQuery s click() function). Angular has similar directives for other events, such as ng-mouseover, ng- keypress, etc See http://www.w3schools.com/angular/angular_events.asp SE-2840 Dr. Mark L. Hornick 19

  20. The ng-app directive SE-2840 Dr. Mark L. Hornick 20

  21. The ng-init directive The ng-init directive is typically placed on a <body> or <div> tag. It is used to declare and initialize variables in the scope of that tag. Use restraint with the ng-init directive Use to mainly to declare/initialize simple variables direcly in the html Don t use complex Javascript expressions. If initialization of variables is not simple , then put the initialization into a Controller SE-2840 Dr. Mark L. Hornick 21

  22. The ng-model directive SE-2840 Dr. Mark L. Hornick 22

  23. The scope The scope is the binding part between the HTML (View) and the JavaScript (Controller). You use the ng-model directive to specify a variable to associate with an input. <input ng-model='cost' type='text' /> A JavaScript variable cost is added to the $scope object of the Controller (ie $scope.cost ) The variable does not have to be pre-defined The ng-model directive effectively defines it See http://www.w3schools.com/angular/angular_scopes.asp SE-2840 Dr. Mark L. Hornick 23

  24. The Controller Controllers are used to augment the scope You can define additional JavaScript variables and functions within the Controller The variables and functions defined in the Controller as part of the Controller s $scope will be available to the template (html) at the point where the Controller is declared: <div ng-controller= myController"> NOTE: regular javascript variables can also be used in a Controller, but they will not be visible to the template. A single (html) template may declare more than one Controller to help define scope boundaries. SE-2840 Dr. Mark L. Hornick 24

  25. Controller and scope example x is visible to the entire template; it s at the root scope <body ng-app="myApp" ng-init="x=1"> x, y, and doSomething() are only visible in this <div>; this <div> has a separate scope <div ng-controller="myController" ng-init="x=17; y=2"> </div> <div ng-controller="secondController" ng-init="z=3"> <p>Value of z is {{z}} </p> </div> z is only visible in the scope of this div <script> var myApp = angular.module('myApp', []); $root.x = 1; // visible throughout the app, unless hidden myApp.controller('myController', function ($scope) { // x and y are only visible in this controller s scope $scope.x = 1; // x in this scope hides x in the root scope $scope.y = 2; $scope.doSomething = function() { }; // some function var abc = 0; // this variable can NOT be used in the <div> in as {{abc}} }); x (from above) is accessible here as $scope.$root.x myApp.controller('secondController', function ($scope) { $scope.z = 3; // z is only visible in this controller s scope }); z is available to the div as {{z}} </script> SE-2840 Dr. Mark L. Hornick 25

  26. View, Controller, and Scope $scope is an object that is used to share data between the View and Controller $scope.x in the Controller is {{x}} in the View Each controller gets its own $scope Controllers do not share $scope This allows for separation and compartmentalization of data They can share data through a $service (not covered) Controllers can access the rootscope as $scope.$root SE-2840 Dr. Mark L. Hornick 26

  27. Angular Filters A filter formats the value of an expression {{3.14159|number:1}} results in 3.1 <li ng-repeat= x in items| orderBy: name > {{entry['pdist']/5280|number:4}} Angular provides many built-in filters See http://www.w3schools.com/angular/angular_filters.asp You can also create custom filters (not covered) SE-2840 Dr. Mark L. Hornick 27

  28. AngularJS Forms SE-2840 Dr. Mark L. Hornick 28

  29. Forms and CSS Styling SE-2840 Dr. Mark L. Hornick 29

  30. Showing and hiding Use ng-show and ng-hide directives to show/hide html elements <!-- show only if $scope.isError is true --> <p ng-show= isError >An error occurred!</p> <!-- show only if $scope.isHidden is true --> <p ng-hide= isHidden >Normally hidden text.</p> Just change isError/isHidden from true to false to show/hide SE-2840 Dr. Mark L. Hornick 30

  31. Services AngularJS provides a number of services, such as: $log (replaces console.log() ) $http (replaces $ajax() of jQuery) $interval (replaces window.setInterval() $timeout (replaces window.setTimeout() These and about 30 more are described at http://www.w3schools.com/angular/angular_services.asp SE-2840 Dr. Mark L. Hornick 31

  32. Example: $log service SE-2840 Dr. Mark L. Hornick 32

  33. $http service This service is the replacement for jQuery s $ajax() function Demo (ngPhone.html) SE-2840 Dr. Mark L. Hornick 33

More Related Content