기본 콘텐츠로 건너뛰기

angular.js 기본문법.


1. angular.js

angular.js 다운 및 공식사이트: https://www.angularjs.org/

대략적인 소감을 약간 극단적으로 표현한다면.
jquery나 jstl이 html을 찍접댄다고한다면,
angular.js는 html을 통으로 가지고 노는 느낌.

2. 기본문법.

<html ng-app="phonecatApp">
<head>
  ...
  <script src="bower_components/angular/angular.js"></script>
  <script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">

  <ul>
    <li ng-repeat="phone in phones">
      <span>{{phone.name}}</span>
      <p>{{phone.snippet}}</p>
    </li>
  </ul>

</body>
</html>

여기서 일반적인html코드와 다른 부분은
ng-app, ng-controller, ng-repeat, {{}} 이정도 이다.
이부분만 이해해도 대충 helloworld는 찍은 것 같다.
angular.js 는 말그대로 라이브러리고,
controller.js는 파일이름 그대로
현재 html에서 angular.js로 작성해야될 controller이다.


ng-app
이 html에서 angular가 적용되는 영역이다.
이영역은 각각의 ng-controller에 의해 구성된다.

<li ng-repeat="phone in phones">
      <span>{{phone.name}}</span>
      <p>{{phone.snippet}}</p>
</li>
처음보는 문법이지만 별로 낯설지는 않다.
phones는 PhoneListCtrl에서 정의된 복수형 변수이고,
phones의 각 item은 phone 으로 핸들링 된다.
jsp에서 java 코드를 <% %>안에 작성했다면,
angular에서는 {{}} 안에 작성한다.


controllers.js
var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});

controller를 호출하는 방식은 다음과 같다. ng-app이 이름이 필요하다.

var phonecatApp = angular.module('phonecatApp', []);
그리고 위에서 설명한 phones는 이렇게 생겻다.
주의할점은 변수 생성시 $scope parameter를 사용한다.
phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});


출처 : https://docs.angularjs.org/tutorial/step_02






댓글