AngularJS Tutorial 2015. 7. 중부대학교 이병천 교수 http://www.w3schools.com/angular/ 중부대학교 이병천 교수
AngularJS란? 기존의 HTML에 새로운 속성을 사용할 수 있도록 만든 자바스크립트 프레임워크 Single Page Application (SPA) 개발에 유용한 도구 2009년에 구글의 Misko Hevery가 개발 시작 2012년에 AngularJS v1.0 발표 Misko Hevery http://misko.hevery.com/
예제 첫번째 예제 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <body> <div ng-app=""> <p>Input something in the input box:</p> <p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p> <h1>Hello {{name}}</h1> </div> </body> </html>
용어 지시자(Directives): ng-directives ng-app : AngularJS 어플리케이션을 정의 ng-model : input, select, textarea 등의 HTML 요소의 값을 어플 리케이션 데이터로 사용할 수 있도록 bind ng-bind : 어플리케이션 데이터를 HTML View로 bind ng-init : 어플리케이션의 변수를 초기화 ng-controller : 콘트롤러를 정의 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="" ng-init="name='sultan'"> <p>Input something in the input box:</p> <p>Name: <input type="text" ng-model="name"></p> <p ng-bind="name"></p> </div> </body> </html>
용어 표현식 (Expressions) AngularJS에서 표현식은 이중괄호로 둘러싸서 표시 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app=""> <p>Input something in the input box:</p> <p>Name: <input type="text" ng-model="name"></p> <p>Your name is {{name}}</p> <p>5+10 = {{5+10}} </p> </div> </body> </html>
예제 총 금액 계산기 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div data-ng-app="" data-ng-init="quantity=1;price=5"> <h2>Cost Calculator</h2> Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price"> <p><b>Total in dollar:</b> {{quantity * price}}</p> </div> </body> </html>
HTML 요소의 반복 표현 Ng-repeat 지시자 이용 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="" ng-init="names=[{name:'Jani',country:'Norway'},{name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'}]"> <p>Looping with objects:</p> <ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.country }}</li> </ul> </div> </body> </html>
AngularJS 컨트롤러 AngularJS 컨트롤러 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="personCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{fullName()}} </div> <script> var app = angular.module('myApp', []); app.controller('personCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; $scope.fullName = function() { return $scope.firstName + " " + $scope.lastName; } }); </script> </body> </html>
컨트롤러의 분리 운영 컨트롤러를 외부 파일로 운영하는 방식 어플리케이션의 규모가 커지면 별도로 운영하는 것이 바람직 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="personCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{firstName + " " + lastName}} </div> <script src="personController.js"></script> </body> </html> // personController.js (외부파일) var app = angular.module('myApp', []); app.controller('personCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; $scope.fullName = function() { return $scope.firstName + " " + $scope.lastName; } });
AngularJS 필터 필터 설명 currency 통화 양식으로 표시 filter 배열에서 주어진 조건과 일치하는 내용을 표시 lowercase String을 소문자로 표시 orderBy 주어진 조건으로 정렬 uppercase String을 대문자로 표시
AngularJS 필터 orderBy 필터 사례 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="namesCtrl"> <p>Looping with objects:</p> <ul> <li ng-repeat="x in names | orderBy:'country'"> {{ x.name + ', ' + x.country }} </li> </ul> </div> <script src="namesController.js"></script> </body> </html>
AngularJS 필터 currency 필터 사례 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="costCtrl"> Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price"> <p>Total = {{ (quantity * price) | currency }}</p> </div> <script> var app = angular.module('myApp', []); app.controller('costCtrl', function($scope) { $scope.quantity = 1; $scope.price = 9.99; }); </script> </body> </html>
$http를 이용한 원격지 서버 데이터 읽기 AngularJS의 $http는 웹서버로부터 데이터를 읽어올 수 있는 XMLHttpRequest 서비스. $http.get(url) 함수 이용 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="customersCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.get("http://www.w3schools.com/angular/customers.php") .success(function (response) {$scope.names = response.records;}); }); </script> </body> </html>
데이터를 테이블로 표시하기 <!DOCTYPE html> <html> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; table tr:nth-child(even) { background-color: #ffffff; </style> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="customersCtrl"> <table> <tr ng-repeat="x in names"> <td>{{ $index + 1 }}</td> <td>{{ x.Name }}</td> <td>{{ x.Country }}</td> </tr> </table> </div> <script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.get("http://www.w3schools.com/angular/customers.php") .success(function (response) {$scope.names = response.records;}); }); </script> </body> </html>
AngularJS HTML DOM DOM을 제어하는 지시자들 ng-disabled ng-show ng-hide <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="" ng-init="mySwitch=true"> <p><button ng-disabled="mySwitch">Click Me!</button></p> <p><input type="checkbox" ng-model="mySwitch"/>Button</p> <p>ng-disabled: {{ mySwitch }}</p> <p ng-show="true">ng-show=true; I am visible.</p> <p ng-show="false">ng-show=false; I am not visible.</p> <p ng-hide="true">ng-hide=true; I am not visible.</p> <p ng-hide="false">ng-hide=false; I am visible.</p> </div> </body> </html>
AngularJS Events 이벤트를 다루는 지시자들 ng-click <!DOCTYPE html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <button ng-click="count = count + 1">Click Me!</button> <p>Count: {{ count }}</p> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.count = 0; }); </script> </body> </html>
AngularJS Events <div ng-app="myApp" ng-controller="personCtrl"> <button ng-click="toggle()">Toggle</button> <p ng-hide="myVar"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{firstName + " " + lastName}} </p> </div> <script> var app = angular.module('myApp', []); app.controller('personCtrl', function($scope) { $scope.firstName = "John", $scope.lastName = "Doe" $scope.myVar = false; $scope.toggle = function() { $scope.myVar = !$scope.myVar; }; }); </script>
모듈과 콘트롤러의 분리 // myApp.js 모듈 var app = angular.module("myApp", []); <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> {{ firstName + " " + lastName }} </div> <script src="myApp.js"></script> <script src="myCtrl.js"></script> </body> </html> // myApp.js 모듈 var app = angular.module("myApp", []); // myCtrl.js 콘트롤러 app.controller("myCtrl", function($scope) { $scope.firstName = "John"; $scope.lastName= "Doe"; });
AngularJS Forms Input, select, button, textarea 등의 요소 제어 <div ng-app="myApp" ng-controller="formCtrl"> <form novalidate> First Name:<br> <input type="text" ng-model="user.firstName"><br> Last Name:<br> <input type="text" ng-model="user.lastName"> <br><br> <button ng-click="reset()">RESET</button> </form> <p>form = {{user}}</p> <p>master = {{master}}</p> </div> <script> var app = angular.module('myApp', []); app.controller('formCtrl', function($scope) { $scope.master = {firstName: "John", lastName: "Doe"}; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); }); </script>
노트 어플리케이션 // myNoteApp.js 모듈 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body ng-app="myNoteApp" ng-controller="myNoteCtrl"> <h2>My Note</h2> <textarea ng-model="message" cols="40" rows="10"></textarea> <p> <button ng-click="save()">Save</button> <button ng-click="clear()">Clear</button> </p> <p>Number of characters left: <span ng-bind="left()"></span></p> <script src="myNoteApp.js"></script> <script src="myNoteCtrl.js"></script> </body> </html> // myNoteApp.js 모듈 var app = angular.module("myNoteApp", []); // myNoteCtrl.js 콘트롤러 app.controller("myNoteCtrl", function($scope) { $scope.message = ""; $scope.left = function() {return 100 - $scope.message.length;}; $scope.clear = function() {$scope.message = "";}; $scope.save = function() {alert("Note Saved");}; });