Skip to content

AngularJS 치트시트

JavaScript 기반 프론트엔드 웹 프레임워크 (Angular 1.x)입니다.

01

시작하기

설정과 부트스트랩

AngularJS(1.x)는 script 태그로 포함합니다. ng-app이 애플리케이션을 부트스트랩하고, ng-controller가 컨트롤러를 DOM 서브트리에 연결합니다. 이중 중괄호 {{ }}는 모델 데이터를 렌더링하는 Angular 표현식입니다.

angularjs
<!-- include AngularJS 1.8.x -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="MainCtrl">
    {{ message }}
  </div>
</body>

<script>
  var app = angular.module('myApp', []);
  app.controller('MainCtrl', function($scope) {
    $scope.message = 'Hello AngularJS!';
  });
</script>

ng-app과 자동 부트스트랩

모듈 이름과 함께 쓴 ng-app은 DOMContentLoaded에서 AngularJS를 자동 부트스트랩합니다. ng-strict-di는 명시적 의존성 어노테이션을 강제해 minification 버그를 개발 중에 일찍 잡아 줍니다. 페이지당 자동 부트스트랩되는 ng-app은 하나뿐입니다.

angularjs
<!-- ng-app on <html> makes the whole page an Angular app -->
<html ng-app="myApp" ng-strict-di>
  <head><title>App</title></head>
  <body>
    <div>{{ 1 + 2 }}</div>
  </body>
</html>

<!-- ng-strict-di enforces dependency injection annotations -->
<!-- (errors if a service uses implicit DI without annotation) -->

수동 부트스트랩

시작을 지연해야 할 때(비동기 모듈 로딩이나 설정 fetch 대기 등) angular.bootstrap()을 사용하세요. 이 방식으로 한 페이지에 여러 Angular 앱을, 각각 자체 루트 엘리먼트로 부트스트랩할 수 있습니다.

angularjs
<!-- HTML has NO ng-app attribute -->
<div id="appRoot">
  {{ message }}
</div>

<script>
  angular.element(document).ready(function() {
    angular.bootstrap(document.getElementById('appRoot'), ['myApp']);
  });
</script>

첫 데이터 바인딩

모듈 이름 없이 ng-app만 쓰면 Angular는 기본 ng 모듈의 'auto' 모드로 실행됩니다. ng-model이 input을 암묵적 스코프의 'name' 프로퍼티에 바인딩하고, {{ }}가 실시간으로 렌더링합니다. 가장 단순한 형태의 양방향 데이터 바인딩입니다.

angularjs
<div ng-app>
  <label>Your name:
    <input type="text" ng-model="name">
  </label>
  <p>Hello {{ name || 'stranger' }}!</p>
</div>

모듈과 컨트롤러 기본

angular.module('name', [deps])은 모듈을 생성하고, angular.module('name')은 기존 모듈을 가져옵니다. 인라인 배열 어노테이션 ['$scope', function($scope){}]은 컨트롤러를 minification에 안전하게 유지합니다. 모듈 생성 시 의존성을 항상 명시적으로 전달하세요.

angularjs
var app = angular.module('myApp', []); // create module
//          ^name   ^dependencies

app.controller('GreetCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' };
  $scope.greet = function() {
    return 'Hi ' + $scope.user.name;
  };
}]);
02

모듈

모듈 생성 vs 조회

인자가 두 개인 angular.module(name, deps)은 새 모듈을 생성합니다. 인자가 하나인 angular.module(name)은 이전에 정의한 모듈을 가져옵니다. 실수로 []를 두 번 전달하면 모듈의 등록이 조용히 사라집니다.

angularjs
// CREATE a module (second arg = dependency array)
var app = angular.module('myApp', []);

// RETRIEVE an existing module (NO second arg)
// var app = angular.module('myApp');

// common mistake: passing [] again overwrites the module

모듈 의존성

의존성 배열에는 프로바이더가 이 모듈에 주입될 모듈들을 나열합니다. ngRoute 같은 내장 모듈은 선택 사항이며 명시적으로 나열하고(스크립트도 로드하고) 해야 합니다. 서브 모듈로 큰 앱을 재사용 가능한 조각으로 나눌 수 있습니다.

angularjs
var app = angular.module('myApp', [
  'ngRoute',          // built-in routing
  'ngAnimate',        // animation hooks
  'ui.router',        // 3rd-party router
  'myApp.common',     // your own sub-module
]);

Config 블록

config()는 서비스 인스턴스가 만들어지기 전, 프로바이더 등록 단계에서 실행됩니다. Provider(예: $routeProvider, $locationProvider)를 주입해 설정할 수 있는 유일한 곳입니다. 라우트 설정, HTML5 모드 활성화, 커스텀 밸리데이터 등록에 사용합니다.

angularjs
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', { templateUrl: 'home.html' })
    .when('/about', { templateUrl: 'about.html' })
    .otherwise({ redirectTo: '/home' });
}]);

Run 블록

run()은 인젝터가 만들어지고 모든 프로바이더가 설정된 후 실행됩니다 — 앱의 'main' 진입점입니다. 인스턴스를 주입합니다(프로바이더 아님). 라우트 변경이나 인증 검사를 위한 전역 $rootScope 리스너 등록에 흔히 사용됩니다.

angularjs
app.run(['$rootScope', 'AuthService', function($rootScope, AuthService) {
  $rootScope.$on('$routeChangeStart', function(event, next) {
    if (!AuthService.isAuthenticated()) {
      event.preventDefault();
    }
  });
}]);

constant와 value

constant()는 config() 블록에도 주입할 수 있는 값을 등록합니다 — 프로바이더가 필요로 하는 설정에 이상적입니다. value()는 run 단계 구성요소(서비스, 컨트롤러)에만 주입됩니다. 일찍 필요한 설정에는 constant를 사용하세요.

angularjs
// constant: available in BOTH config and run phases
app.constant('API_BASE', 'https://api.example.com');

// value: available only in run phase (injectable as instance)
app.value('defaultPageSize', 20);

// usage in a service:
app.factory('UserSvc', ['API_BASE', function(API_BASE) {
  return { all: function() { /* use API_BASE */ } };
}]);
03

컨트롤러

기본 컨트롤러

컨트롤러는 $scope의 초기 상태를 설정하고 동작(함수)을 추가합니다. 컨트롤러는 얇게 유지하세요 — 비즈니스 로직은 서비스에 들어갑니다. 컨트롤러 생성자는 컨트롤러의 새 인스턴스가 필요할 때마다(예: ng-controller 사용마다) 실행됩니다.

angularjs
app.controller('TodoCtrl', ['$scope', function($scope) {
  $scope.todos = [
    { text: 'Learn AngularJS', done: true },
    { text: 'Build an app', done: false }
  ];

  $scope.addTodo = function() {
    $scope.todos.push({ text: $scope.todoText, done: false });
    $scope.todoText = '';
  };

  $scope.remaining = function() {
    return $scope.todos.filter(function(t) { return !t.done; }).length;
  };
}]);

controllerAs 문법

controllerAs는 컨트롤러 인스턴스를 별칭(main)으로 스코프에 게시합니다. 프로퍼티와 메서드에 $scope 대신 this를 사용하세요. $scope 상속의 함정을 피하고, 중첩 뷰에서 프로퍼티가 어느 컨트롤러에서 왔는지 명확해 집니다.

angularjs
<div ng-controller="MainCtrl as main">
  <p>{{ main.title }}</p>
  <button ng-click="main.save()">Save</button>
</div>

<script>
app.controller('MainCtrl', function() {
  this.title = 'Controller As';
  this.save = function() { /* ... */ };
});
</script>

Minification 안전 DI

Minifier는 함수 파라미터 이름을 바꿔버려서 Angular의 이름 기반 의존성 추론이 깨집니다. 인라인 배열 어노테이션은 함수 앞에 서비스 이름을 문자열로 나열하므로 minification 후에도 이름이 살아남습니다. 항상 이 어노테이션이나 ng-annotate / $inject를 사용하세요.

angularjs
// SAFE: inline array annotation (parameter names are string literals)
app.controller('SafeCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('/api/items').then(function(res) { $scope.items = res.data; });
}]);

// UNSAFE: implicit DI breaks when minified
app.controller('UnsafeCtrl', function($scope, $http) { /* ... */ });

$inject 프로퍼티 어노테이션

인라인 배열의 대안으로, 생성자 함수에 서비스 이름 배열인 $inject를 붙입니다. 함수 선언이 읽기 쉽고 재사용 가능하게 유지됩니다. 두 스타일은 동등합니다 — 하나를 정해서 일관되게 쓰세요(또는 ng-annotate로 자동화).

angularjs
function UserCtrl($scope, UserService) {
  UserService.list().then(function(users) {
    $scope.users = users;
  });
}
// explicit dependency list on the function
UserCtrl.$inject = ['$scope', 'UserService'];

app.controller('UserCtrl', UserCtrl);

중첩 컨트롤러와 상속

자식 스코프는 부모 스코프를 프로토타입 상속하므로 자식 컨트롤러가 부모 프로퍼티를 읽을 수 있습니다. 하지만 자식에 원시값을 할당하면 부모를 업데이트하는 대신 부모를 가리는 새 로컬 프로퍼티가 생깁니다 — 흔한 함정입니다. 객체(점 표기법)나 controllerAs를 사용해 피하세요.

angularjs
<div ng-controller="ParentCtrl">
  <p>{{ shared }}</p>      <!-- sees parent's 'shared' -->
  <div ng-controller="ChildCtrl">
    <p>{{ shared }}</p>    <!-- inherits, can shadow -->
    <p>{{ childOnly }}</p>
  </div>
</div>

app.controller('ParentCtrl', ['$scope', function($scope) {
  $scope.shared = 'from parent';
}]);
app.controller('ChildCtrl', ['$scope', function($scope) {
  $scope.childOnly = 'child only';
  $scope.shared = 'overridden by child'; // shadows parent
}]);

컨트롤러 정리 ($destroy)

$scope의 $destroy 이벤트를 구독하면 컨트롤러 스코프가 해체될 때(예: 페이지 이동) 정리 작업을 실행할 수 있습니다. $interval/$timeout 타이머를 취소하고, window 리스너를 해제하며, 참조를 놓아 누수를 막으세요. Angular가 자체 스코프 watcher는 자동 정리합니다.

angularjs
app.controller('TimerCtrl', ['$scope', '$interval', function($scope, $interval) {
  var timer = $interval(function() { $scope.now = Date.now(); }, 1000);

  $scope.$on('$destroy', function() {
    $interval.cancel(timer); // free the resource
  });
}]);
04

$scope

$scope 기본

$scope는 컨트롤러와 뷰 사이의 접착제입니다 — 템플릿이 바인딩하는 모델과 동작을 담습니다. Angular는 컨트롤러마다 새 스코프를 만들며, 템플릿의 표현식은 그 스코프(과 부모들)를 기준으로 평가됩니다.

angularjs
app.controller('MsgCtrl', ['$scope', function($scope) {
  $scope.message = 'Hi';          // model on scope
  $scope.count = 0;
  $scope.inc = function() {
    $scope.count++;
  };
}]);

// In HTML: {{ message }}, {{ count }}, ng-click="inc()"

스코프 상속 (프로토타입)

자식 스코프는 JavaScript 프로토타입 체인으로 부모 스코프를 상속합니다. 부모 프로퍼티 읽기는 되지만, 자식에서 원시값을 할당하면(예: $scope.name = 'x') 부모를 가리는 로컬 복사본이 생깁니다. 객체(user.name)에 바인딩해야 쓰기가 체인 위로 전파됩니다.

angularjs
<!-- primitive on parent: child writes a NEW copy -->
<div ng-controller="ParentCtrl">
  <div ng-controller="ChildCtrl">
    <input ng-model="name"> <!-- shadows parent.name -->
  </div>
</div>

<!-- object avoids the shadowing gotcha -->
app.controller('ParentCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' }; // child edits user.name -> updates parent
}]);

$rootScope

$rootScope는 스코프 계층의 정점이며 모든 스코프가 여기서 파생됩니다. 여기 둔 프로퍼티는 모든 템플릿에서 보입니다. 진짜 전역 값(앱 이름, 세션 플래그)에만 절제해서 사용하세요 — 남용하면 숨은 결합이 생기고 상태 추적이 어려워집니다.

angularjs
app.run(['$rootScope', function($rootScope) {
  $rootScope.appName = 'MyApp';     // available everywhere
  $rootScope.version = '1.0';
}]);

<!-- any template -->
<footer>© {{ appName }} {{ version }}</footer>

스코프 이벤트: $emit / $broadcast / $on

$emit은 이벤트를 $rootScope까지 위로 전파하고, $broadcast는 모든 자식 스코프로 아래로 전파합니다. $on은 리스너를 등록하고 해제 함수를 반환합니다. 데이터는 두 번째 인자로 전달합니다. 누수를 피하려면 $destroy에서 리스너를 해제하세요.

angularjs
// travel UP toward $rootScope
$scope.$emit('userLoggedOut', { userId: 7 });

// travel DOWN to all descendant scopes
$scope.$broadcast('itemAdded', { id: 99 });

// listen for an event
var unbind = $scope.$on('itemAdded', function(event, args) {
  console.log('item', args.id);
});
// stop listening when scope is destroyed
$scope.$on('$destroy', unbind);

$new, $id, $parent

$new(isolated, parent)는 자식(또는 isolate) 스코프를 만들고, $id는 고유 숫자 id, $parent는 부모 스코프를 참조합니다. 대부분 디렉티브 내부에서 사용됩니다. 수동으로 만든 스코프에는 반드시 $destroy()를 호출해 watcher를 제거하고 메모리 누수를 막으세요.

angularjs
var child = $scope.$new();        // create a child scope
child.extra = 'child data';
console.log(child.$id);          // unique scope id
console.log(child.$parent === $scope); // true
// ...
child.$destroy();                // remove from hierarchy

Isolate 스코프 (디렉티브 미리보기)

디렉티브에서 scope: {}를 설정하면 부모로부터 프로토타입 상속하지 않는 isolate 스코프가 만들어집니다 — 재사용 가능한 컴포넌트에 필수입니다. 부모는 선언된 바인딩(@, =, &)으로만 통신합니다. 컴포넌트가 주변 스코프를 우연히 읽거나 오염시키는 것을 막아 줍니다.

angularjs
app.directive('userCard', function() {
  return {
    scope: {              // ISOLATE scope: does NOT inherit parent
      user: '=',          // two-way binding
      onKick: '&'         // expression binding
    },
    template: '<p>{{ user.name }}</p>'
  };
});

<!-- usage -->
<user-card user="currentUser" on-kick="removeUser()"></user-card>
05

표현식

기본 표현식

Angular 표현식은 JavaScript 비슷하지만 window가 아닌 $scope 기준으로 평가됩니다. 산술, 문자열 연결, 멤버 접근, 삼항 연산자를 지원합니다. JS와 달리 undefined/null은 빈 문자열로 표시됩니다('undefined' 텍스트 없음). 옵셔널 체이닝 연산자는 지원하지 않습니다.

angularjs
<p>{{ 1 + 2 }}</p>                <!-- 3 -->
<p>{{ 'Hello, ' + name }}</p>
<p>{{ user.name }}</p>
<p>{{ items.length }} items</p>
<p>{{ obj?.nested }}</p>           <!-- AngularJS does NOT support ?. -->

표현식 vs JavaScript

표현식은 JS보다 제한적입니다: 문(if/for/while) 불가, new/throw 불가, 콤마 불가, 함수 정의 불가, 일부 버전에서는 비트 연산 불가. $scope를 컨텍스트로 평가되며 오류를 조용히 삼킵니다($exceptionHandler에 기록). 이 덕분에 템플릿이 안전하고 선언적으로 유지됩니다.

angularjs
<!-- ALLOWED in expressions -->
{{ a + b }}
{{ cond ? 'yes' : 'no' }}
{{ user.getName() }}
{{ [1,2,3].length }}

<!-- NOT allowed: control flow, new, throw, comma operator -->
{{ if (x) { ... } }}     <!-- SyntaxError -->
{{ throw new Error() }}  <!-- not allowed -->

일회성 바인딩 (::)

:: 접두사는 일회성 바인딩을 만듭니다: Angular가 표현식을 평가하고 정의되면(즉 undefined가 아니면) watcher를 제거합니다. digest 사이클의 watcher 수를 크게 줄여, 초기 로드 후 바뀌지 않는 데이터의 성능을 개선합니다.

angularjs
<!-- AngularJS 1.3+ -->
<p>{{ ::user.name }}</p>           <!-- evaluated once, then unwatched -->
<li ng-repeat="item in ::items">{{ ::item.label }}</li>

<!-- good for static data that never changes -->
<h1>{{ ::conferenceTitle }}</h1>

$eval과 $parse

$scope.$eval(expr)은 스코프 기준으로 표현식 문자열을 파싱하고 실행합니다. $parse는 표현식을 한 번 컴파일해 재사용 가능한 getter/setter 함수로 만듭니다 — 문자열을 반복 평가하는 것보다 훨씬 효율적입니다. 표현식 바인딩을 소비하는 디렉티브/서비스 내부에서 $parse를 사용하세요.

angularjs
// evaluate an expression against $scope
var result = $scope.$eval('1 + 2 * count');   // 1 + 2*count
// $scope.$eval(expr, locals)

// compile once, reuse: more efficient for repeated eval
var getter = $parse('user.name');
var name = getter($scope);
getter.assign($scope, 'Ada'); // two-way: sets user.name

표현식의 필터

파이프 |는 표현식에 필터를 적용하며, 여러 필터는 왼쪽에서 오른쪽으로 체이닝됩니다. 인자는 콜론으로 전달합니다. 필터는 편리하지만 매 digest마다 다시 실행됩니다 — 큰 목록은 $filter나 computed 프로퍼티로 컨트롤러에서 필터링하는 것이 성능상 좋습니다.

angularjs
<p>{{ price | currency }}</p>             <!-- $1.99 -->
<p>{{ today | date:'yyyy-MM-dd' }}</p>    <!-- 2025-01-01 -->
<p>{{ name | uppercase }}</p>
<p>{{ items | filter:query | orderBy:'name' }}</p>

<!-- chained with |, arguments after : -->

ng-bind와 ng-cloak

Angular가 부트스트랩되기 전에는 브라우저가 {{ }} 텍스트를 그대로 보여 줍니다('컴파일 안 된 콘텐츠 깜빡임'). ng-bind는 Angular가 실행된 후에만 요소의 텍스트에 값을 쓰므로 깜빡임을 피합니다. ng-cloak은 CSS 규칙과 함께 Angular가 컴파일할 때까지 요소를 숨깁니다.

angularjs
<!-- raw {{ }} may flash before Angular compiles -->
<p>{{ message }}</p>

<!-- ng-bind avoids the flash -->
<p ng-bind="message"></p>

<!-- ng-cloak hides elements until compiled -->
<style>[ng-cloak] { display: none; }</style>
<p ng-cloak>{{ message }}</p>
06

내장 디렉티브

ng-model (양방향 바인딩)

ng-model은 폼 input을 스코프 프로퍼티에 양방향으로 동기화합니다: input 변경이 모델을, 모델 변경이 input을 업데이트합니다. input, textarea, select, checkbox/radio에서 동작합니다. 원시값 가림 문제를 피하려면 항상 점 표기 프로퍼티(user.name)에 바인딩하세요.

angularjs
<input type="text" ng-model="user.name">
<p>Hello, {{ user.name }}</p>

<!-- checkbox binds to boolean -->
<input type="checkbox" ng-model="agree"> I agree

<!-- select binds the chosen option's value -->
<select ng-model="color">
  <option value="r">Red</option>
  <option value="g">Green</option>
</select>

ng-repeat

ng-repeat은 컬렉션의 항목마다 엘리먼트를 복제합니다. $index, $first, $last, $middle, $even, $odd가 노출됩니다. 항상 track by로 안정적인 식별자를 주세요 — Angular가 배열이 바뀌어도 DOM 노드를 재사용해 전체 리렌더를 피하고 중복 키 오류도 해결합니다.

angularjs
<ul>
  <li ng-repeat="item in items track by item.id">
    {{ $index }}: {{ item.name }}
    <span ng-if="$first">(first)</span>
    <span ng-if="$last">(last)</span>
  </li>
</ul>

<!-- ng-repeat over object -->
<li ng-repeat="(key, value) in config">{{ key }} = {{ value }}</li>

ng-if / ng-show / ng-hide

ng-if는 조건에 따라 엘리먼트(과 자식 스코프)를 DOM에 삽입/제거합니다 — 토글 비용은 크지만 숨겨놨을 때가 저렴합니다. ng-show/ng-hide는 CSS 클래스만 바꾸고 엘리먼트를 DOM에 유지합니다 — 토글은 저렴하지만 엘리먼트가 항상 컴파일됩니다. 드물게 보이는 콘텐츠에는 ng-if를 선호하세요.

angularjs
<!-- ng-if: removes/adds element from DOM -->
<div ng-if="user.isAdmin">Admin tools</div>

<!-- ng-show/ng-hide: toggles display:none only -->
<div ng-show="isLoading">Loading...</div>
<div ng-hide="isLoggedIn">Please log in</div>

ng-class와 ng-style

ng-class는 객체(truthy 키가 클래스가 됨), 클래스 이름 배열, 문자열을 받습니다. ng-style은 CSS 프로퍼티 이름과 값의 매핑 객체를 받습니다. 둘 다 매 digest마다 재평가되므로 정적 스타일은 일반 class 속성을 쓰고, 상태 기반 스타일에 이것들을 사용하세요.

angularjs
<!-- object form: keys are classes, truthy values apply them -->
<div ng-class="{ active: tab === 1, disabled: !enabled }"></div>

<!-- array form -->
<div ng-class="[styleA, styleB]"></div>

<!-- ng-style: object of CSS properties -->
<div ng-style="{ color: theme.color, 'font-size': theme.size + 'px' }">
  Styled text
</div>

ng-bind-template과 ng-init

ng-bind-template은 여러 표현식을 {{ }} 없이 엘리먼트 텍스트에 바인딩합니다. ng-init은 엘리먼트 초기화 시 표현식을 한 번 평가합니다 — 데모에는 편리하지만 마크업에 로직을 넣는 셈이라 실제 앱에서는 권장되지 않습니다. 초기 상태는 컨트롤러에서 설정하세요.

angularjs
<!-- bind multiple expressions to text -->
<p ng-bind-template="Hello {{ first }} {{ last }}"></p>

<!-- ng-init: set a local (use sparingly, prefer controller) -->
<div ng-init="qty = 1; cost = 5">
  Total: {{ qty * cost }}
</div>

ng-src / ng-href / ng-disabled

src='{{ }}' 대신 ng-src와 ng-href를 사용하세요. Angular가 보간하기 전에 브라우저가 문자 그대로의 '{{ }}' URL로 요청을 보내는 것을 막아 줍니다. ng-disabled는 표현식에 따라 disabled 속성을 토글합니다 — 폼이 유효하지 않거나 요청 중일 때 제출 버튼을 비활성화하기에 완벽합니다.

angularjs
<!-- avoid broken requests before binding resolves -->
<img ng-src="{{ user.avatarUrl }}" alt="avatar">
<a ng-href="{{ profileUrl }}">Profile</a>

<button ng-disabled="form.$invalid || saving">
  {{ saving ? 'Saving...' : 'Save' }}
</button>
07

커스텀 디렉티브

기본 디렉티브

디렉티브는 HTML을 확장합니다. restrict: 'E'는 커스텀 엘리먼트(<greeting>), 'A'는 어트리뷰트로 만듭니다. 가장 단순한 디렉티브는 템플릿만 반환합니다. 기본값으로 Element/Attribute restrict를 사용하고, Class/Comment restrict는 드뭅니다. 모던 모범 사례는 템플릿 기반 디렉티브 대신 컴포넌트를 권합니다.

angularjs
app.directive('greeting', function() {
  return {
    restrict: 'E',              // E=element, A=attr, C=class, M=comment
    template: '<h1>Hello there!</h1>'
  };
});

<!-- usage -->
<greeting></greeting>
<!-- or as attribute: <div greeting></div> -->

디렉티브 정의 객체 (DDO)

Directive Definition Object는 모든 측면을 설정합니다: restrict, scope(isolate 여부), template/templateUrl, transclude, controller, link 함수. templateUrl은 템플릿을 $http로(캐시되어) 로드하고, template은 인라인입니다. DOM 조작은 link에, 뷰모델 로직은 controller에 두세요.

angularjs
app.directive('card', function() {
  return {
    restrict: 'E',
    scope: {},                  // isolate scope
    templateUrl: 'card.html',
    transclude: true,
    controller: function() { /* ... */ },
    controllerAs: 'vm',
    bindToController: {},
    link: function(scope, el, attrs) { /* DOM work */ }
  };
});

Isolate 스코프 바인딩 (@ = &)

@는 어트리뷰트를 문자열로 읽습니다(단방향, 부모→자식, 보간됨). =는 부모의 표현식과 양방향 바인딩을 만듭니다. &는 부모 스코프의 표현식을 실행하는 함수를 노출합니다 — 이벤트 콜백에 사용합니다. 이 세 바인딩이 재사용 가능한 디렉티브 컴포넌트의 핵심입니다.

angularjs
app.directive('profile', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',          // read attribute as STRING (one-way)
      user: '=',          // two-way binding to expression
      onSave: '&'         // callback: evaluate expression in parent scope
    },
    template: '<p>{{ name }} / {{ user.email }}</p>'
  };
});

<profile name="{{ n }}" user="currentUser" on-save="save()"></profile>

Link 함수

link 함수는 디렉티브 엘리먼트가 컴파일된 후 실행됩니다. 직접적인 DOM 조작, 이벤트 리스너(jQuery Lite의 .on), attrs.$observe로 보간된 어트리뷰트 관찰에 사용합니다. scope는 디렉티브의 스코프, element는 jqLite로 감싼 DOM 노드, attrs는 정규화된 어트리뷰트입니다.

angularjs
app.directive('highlight', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('mouseenter', function() {
        element.css('background', 'yellow');
      });
      element.on('mouseleave', function() {
        element.css('background', '');
      });
      attrs.$observe('highlight', function(val) {
        // react to attribute interpolation changes
      });
    }
  };
});

Compile 함수

compile 함수는 Angular가 ng-repeat 등으로 복제하기 전에 원본 템플릿 엘리먼트에 한 번 실행됩니다. 스코프가 필요 없는 템플릿 수준 변형에 사용합니다. link 함수(또는 pre/post link 객체)를 반환합니다. 대부분의 디렉티브는 compile이 필요 없고 인스턴스 작업은 link를 선호합니다.

angularjs
app.directive('repeatN', function() {
  return {
    restrict: 'E',
    compile: function(tElement, tAttrs) {
      // runs ONCE on the TEMPLATE element, before cloning
      var n = parseInt(tAttrs.count, 10);
      for (var i = 1; i < n; i++) {
        tElement.after(tElement.clone());
      }
      // optionally return a (post) link function
      return function link(scope, el, attrs) {
        el.addClass('repeated');
      };
    }
  };
});

트랜스클루전(Transclusion)

transclude: true는 원본 엘리먼트의 콘텐츠를 캡처해 템플릿에서 ng-transclude가 있는 곳에 삽입합니다. 트랜스클루드된 콘텐츠는 디렉티브의 isolate 스코프가 아니라 원래의(부모) 스코프를 유지합니다. 패널, 모달, 카드 같은 래퍼 디렉티브가 호출자가 제공한 임의 콘텐츠를 감쌀 수 있게 합니다.

angularjs
app.directive('panel', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div class="panel"><div class="panel-body" ng-transclude></div></div>'
  };
});

<!-- the inner content lands inside ng-transclude -->
<panel>
  <h3>Title</h3>
  <p>Body content goes here.</p>
</panel>
08

필터(Filters)

내장 필터

Angular는 number, currency, date, lowercase, uppercase, json, limitTo, orderBy, filter 필터를 제공합니다. 콜론 뒤의 인자가 필터를 설정합니다. currency는 ISO 심볼이나 커스텀 문자를 받습니다. 필터는 매 digest마다 다시 실행되므로 무거운 계산은 캐싱하거나 컨트롤러에서 하세요.

angularjs
<p>{{ 1234.5 | number:2 }}</p>          <!-- 1,234.50 -->
<p>{{ 9.99 | currency:'USD' }}</p>     <!-- $9.99 -->
<p>{{ 128 | currency:'&euro;' }}</p>   <!-- €128.00 -->
<p>{{ 'hi' | uppercase }}</p>          <!-- HI -->
<p>{{ 'HI' | lowercase }}</p>          <!-- hi -->
<p>{{ 'a b c' | limitTo:2 }}</p>       <!-- a  -->

date 필터

date 필터는 Date 객체, ISO 8601 문자열, epoch 밀리초를 포맷합니다. 미리 정의된 포맷: 'short','medium','long','full','shortDate','mediumDate','shortTime'. 커스텀 포맷 토큰: y(연도), M(월), d(일), H(시), m(분), s(초), EEEE(전체 요일).

angularjs
<p>{{ now | date }}</p>                       <!-- Jan 1, 2025 -->
<p>{{ now | date:'yyyy-MM-dd' }}</p>        <!-- 2025-01-01 -->
<p>{{ now | date:'shortTime' }}</p>         <!-- 3:45 PM -->
<p>{{ now | date:'EEEE, MMMM d, y' }}</p>   <!-- Wednesday, January 1, 2025 -->

<!-- accepts a Date, ISO string, or millis timestamp -->

filter 필터 (배열 검색)

filter 필터는 문자열, 객체, 술어 함수에 일치하는 배열 항목을 선택합니다. 객체는 지정된 필드가 주어진 값을 포함하는 항목에 매칭됩니다. 선택적 세 번째 인자 true는 정확 일치를 강제합니다. 큰 배열은 digest마다 재실행을 피하려고 컨트롤러에서 필터링하세요.

angularjs
<!-- match any field containing the query string -->
<li ng-repeat="u in users | filter:query">{{ u.name }}</li>

<!-- match a specific field with an object -->
<li ng-repeat="u in users | filter:{ role: 'admin' }">{{ u.name }}</li>

<!-- strict equality on a field -->
<li ng-repeat="u in users | filter:{ id: 5 }:true">{{ u.name }}</li>

orderBy 필터

orderBy는 필드 이름(내림차순은 '-' 접두사), 그런 필드의 배열, 또는 비교자 함수로 배열을 정렬합니다. 매 digest마다 새 정렬 배열을 만드므로 큰 목록은 컨트롤러에서 한 번 정렬해 재사용하세요. filter와 조합하면 검색+정렬 UI를 만듭니다.

angularjs
<!-- ascending by 'name' -->
<li ng-repeat="u in users | orderBy:'name'">{{ u.name }}</li>

<!-- descending -->
<li ng-repeat="u in users | orderBy:'-name'">{{ u.name }}</li>

<!-- multiple fields -->
<li ng-repeat="u in users | orderBy:['role','-age']">{{ u.name }}</li>

<!-- by a function -->
<li ng-repeat="u in users | orderBy:scoreFn">{{ u.name }}</li>

커스텀 필터

app.filter로 필터 팩토리를 등록합니다. 팩토리는 입력(파이프 앞의 값)과 추가 인자를 변환하는 함수를 반환합니다. 필터는 순수하고 부수 효과가 없어야 합니다. 주입 가능하므로 팩토리 안에서 다른 서비스에 의존할 수 있습니다.

angularjs
app.filter('capitalize', function() {
  return function(input) {
    if (!input) return '';
    input = String(input);
    return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
  };
});

<!-- usage -->
<p>{{ 'hELLo' | capitalize }}</p>   <!-- Hello -->

컨트롤러의 $filter 서비스

$filter를 주입하면 JS(컨트롤러, 서비스) 안에서 필터를 적용할 수 있습니다. $filter('name')(value, arg1, arg2) 형태로 호출합니다. 매 digest마다 필터를 다시 실행하는 것을 피하고 결과를 재사용하게 해 줍니다. 뷰뿐 아니라 로직에서 필터된 값이 필요할 때 유용합니다.

angularjs
app.controller('ListCtrl', ['$scope', '$filter', function($scope, $filter) {
  $scope.users = [/* ... */];

  // run the orderBy filter programmatically
  $scope.sorted = $filter('orderBy')($scope.users, 'name');

  // currency filter to format a number
  $scope.priceText = $filter('currency')(99.5, '$');
}]);
09

서비스 ($http, $location, ...)

$http 기본

$http는 XHR 요청을 수행하고 Promise를 반환합니다. 이행되는 값은 data, status, headers, config를 가진 응답 객체입니다. .then이 성공을, .catch가 오류를 처리합니다. Angular 1.6부터 .success/.error 콜백은 제거되었으니 promise의 .then/.catch로 일관되게 쓰세요.

angularjs
app.controller('ApiCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('/api/users')
    .then(function(response) {
      $scope.users = response.data;       // response: {data, status, headers, config}
    })
    .catch(function(error) {
      console.error('failed', error.status);
    });
}]);

설정과 함께 $http POST/PUT

get/post/put/delete/patch/jsonp/head 편의 메서드가 있습니다. 완전한 제어가 필요하면 config 객체를 전달하세요: params는 쿼리 문자열로, headers는 요청 헤더로, responseType은 본문 파싱 방식을 결정합니다. $http는 기본 transform(JSON 파싱)을 자동 적용합니다.

angularjs
$http.post('/api/users', { name: 'Ada' })
  .then(function(res) { console.log('created', res.data); });

// with headers / query params / response type
$http({
  method: 'GET',
  url: '/api/report',
  params: { format: 'pdf' },
  headers: { 'X-Auth': token },
  responseType: 'arraybuffer'
}).then(function(res) { /* res.data is binary */ });

$location 서비스

$location은 브라우저 URL과 digest 사이클과 동기화되는 window.location의 래퍼입니다. path, 검색 파라미터, hash를 읽거나 변경하는 데 사용합니다. HTML5 깔끔한 URL을 켜려면 $locationProvider.html5Mode(true)를 설정하고 <base> 태그를 추가하세요.

angularjs
// read the URL
$location.path();          // '/users/42'
$location.search();        // { tab: 'edit' }
$location.hash();          // 'top'
$location.absUrl();        // full URL

// change without full reload
$location.path('/dashboard');
$location.search('q', 'angular');   // ?q=angular
$location.hash('section-2');

$timeout과 $interval

$timeout과 $interval은 setTimeout/setInterval의 digest 인식 래퍼입니다 — $apply를 트리거해 스코프 업데이트가 반영됩니다. 누수와 '파괴된 스코프에서 digest' 오류를 막으려면 $destroy에서 반드시 취소하세요. digest가 필요 없으면 세 번째 인자로 false를 전달해 건너뛸 수 있습니다.

angularjs
// $timeout: like setTimeout but triggers a $digest
var promise = $timeout(function() {
  $scope.status = 'ready';
}, 1000);

// cancel
$timeout.cancel(promise);

// $interval: like setInterval, also digest-aware
var ticker = $interval(function() { $scope.now = Date.now(); }, 5000);
$scope.$on('$destroy', function() { $interval.cancel(ticker); });

$log와 $window / $document

$log는 console의 얇은 래퍼로 log/info/warn/error/debug를 지원하며 프로덕션 로깅을 위해 decorate할 수 있습니다. $window와 $document는 전역 객체를 감쌉니다 — window/document를 직접 호출하지 말고 항상 주입받으세요. 그래야 테스트에서 목킹할 수 있고 코드가 환경에 독립적으로 유지됩니다.

angularjs
app.controller('LogCtrl', ['$log', '$window', function($log, $window) {
  $log.log('plain');
  $log.info('info');
  $log.warn('warning');
  $log.error('error');

  $window.alert('Hi');      // safer than bare alert()
  $window.innerWidth;
}]);

// $document wraps document; $window wraps window.
// Injecting them (instead of using globals) makes testing easy.

$rootScope.broadcast와 전역 이벤트

앱 전역 이벤트(로그인/로그아웃, 테마 변경)에는 $rootScope.$broadcast를 사용하세요. 모든 스코프의 리스너가 받습니다. $rootScope 리스너만 들어야 하는 이벤트에는 $rootScope.$emit이 더 저렴합니다(아래로 내려가지 않음). 전역 이벤트 남용을 피하고 대부분의 통신은 명시적 API를 가진 서비스로 하세요.

angularjs
// anywhere: broadcast a global event
$rootScope.$broadcast('auth:logout');

// in a controller: listen
$scope.$on('auth:logout', function() {
  $scope.currentUser = null;
});

// $emit on $rootScope = effectively global too
$rootScope.$emit('something', data); // only $rootScope.$on hears this
10

factory, service, provider

factory()

factory()는 서비스 인스턴스를 반환하는 함수를 받습니다 — 팩토리는 한 번 실행되고(싱글턴) 반환 값이 공유됩니다. 서비스를 만드는 가장 흔한 방법으로, 깔끔한 API 뒤에 private 상태를 캡슐화하기 좋습니다. 반환하는 것(객체, 함수, 원시값)이 무엇이든 그것이 서비스가 됩니다.

angularjs
app.factory('UserService', ['$http', function($http) {
  var current = null;            // private state

  return {
    login: function(creds) {
      return $http.post('/login', creds).then(function(res) {
        current = res.data;
        return current;
      });
    },
    getCurrent: function() { return current; },
    isLoggedIn: function() { return !!current; }
  };
}]);

service()

service()는 생성자를 new로 인스턴스화하므로 this에 프로퍼티를 붙입니다. 새 인스턴스를 반환하는 팩토리와 동등하며 둘 다 싱글턴입니다. 생성자/클래스 스타일을 선호하면 service(), 특정 객체를 반환하거나 무언가를 감싸야 하면 factory()를 사용하세요.

angularjs
app.service('Counter', function() {
  // invoked with 'new' -> 'this' is the instance
  this.count = 0;
  this.inc = function() { this.count++; };
  this.reset = function() { this.count = 0; };
});

// usage: Counter.inc(); Counter.count;

provider()

provider()는 가장 저수준의 레시피입니다: 설정 시점의 객체(세터 포함)와 인스턴스를 만드는 $get 팩토리를 노출합니다. config() 블록에 주입되는 것은 프로바이더뿐입니다(접미사 'Provider'). 인스턴스화 전에 설정이 필요하면 provider(), 아니면 factory()를 선호하세요.

angularjs
app.provider('Greeter', function() {
  // config-time: defaults settable from .config()
  this.greeting = 'Hello';        // default

  this.setGreeting = function(g) { this.greeting = g; };

  // factory that produces the service instance
  this.$get = function() {
    var self = this;
    return {
      greet: function(name) { return self.greeting + ', ' + name + '!'; }
    };
  };
});

// configure in a config block:
app.config(['GreeterProvider', function(GreeterProvider) {
  GreeterProvider.setGreeting('Bonjour');
}]);

constant() vs value()

둘 다 간단한 주입 가능한 값을 등록합니다. constant()는 config 단계에서 사용 가능하고(프로바이더가 쓸 수 있음) 불변입니다. value()는 run 단계에서만 사용 가능합니다. 경험 법칙: 프로바이더가 의존하는 설정에는 constant, 공유 런타임 데이터나 헬퍼에는 value를 사용하세요.

angularjs
// constant: injectable in config AND run phases
app.constant('MAX_USERS', 1000);

// value: injectable in run phase only (not config)
app.value('toastConfig', { duration: 3000 });

// value can hold any type, even a function
app.value('logger', function(msg) { console.log(msg); });

factory vs service vs provider

내부적으로 모든 레시피는 provider입니다: factory의 함수가 $get이 되고, service는 생성자를 new하는 팩토리입니다. 가독성으로 선택하세요: 대부분 factory, 생성자 스타일 클래스는 service, 인스턴스화 전 설정이 필요하면 provider. 컴포넌트는 소비만 하므로 선택은 내부 사정입니다.

angularjs
// all three are singletons; the difference is HOW the instance is built

// factory: function returns the instance
app.factory('A', function() { return { x: 1 }; });

// service: constructor is 'new'-ed
app.service('B', function() { this.x = 1; });

// provider: $get returns the instance (configurable)
app.provider('C', function() {
  this.$get = function() { return { x: 1 }; };
});

$provide.decorator()

decorator()는 기존 서비스의 인스턴스화를 가로챕니다 — $delegate가 원본 인스턴스이며 감싸거나, 확장하거나, 교체할 수 있습니다. 원본 서비스를 건드리지 않고 횡단 관심사(로깅, 캐싱, 오류 보고)를 처리할 때 사용합니다. 데코레이터는 서비스가 처음 주입될 때 지연 실행됩니다.

angularjs
app.decorator('$log', ['$delegate', function($delegate) {
  // $delegate is the original $log instance
  var origError = $delegate.error;
  $delegate.error = function(msg) {
    // e.g., send to error tracking, then call original
    trackError(msg);
    origError.apply($delegate, arguments);
  };
  return $delegate;   // return the (modified) service
}]);
11

라우팅 (ngRoute와 ui-router)

ngRoute 설정

ngRoute는 내장 라우터입니다(별도 angular-route.js 파일). .when(path, config)으로 라우트를 등록하고 .otherwise()로 폴백을 만듭니다. ng-view가 매칭된 템플릿+컨트롤러가 렌더링되는 outlet입니다. ngRoute는 outlet 하나와 단순 :param URL만 지원합니다 — 중첩 뷰는 ui-router를 사용하세요.

angularjs
<!-- include angular-route.js (separate file in 1.x) -->
<script src="angular-route.js"></script>

var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', { templateUrl: 'home.html', controller: 'HomeCtrl' })
    .when('/users/:id', { templateUrl: 'user.html', controller: 'UserCtrl' })
    .otherwise({ redirectTo: '/home' });
}]);

<!-- where the matched view renders -->
<div ng-view></div>

ngRoute 라우트 파라미터

$routeParams는 URL 세그먼트(:id)를 문자열 키 객체로 노출합니다 — 값은 항상 문자열이므로 숫자는 parseInt로 변환하세요. 라우트 변경 후 갱신됩니다. 동적 링크에는 ng-href를 사용합니다. 기본 hashbang 접두사는 #!입니다(1.6부터); $locationProvider.hashPrefix('')로 설정합니다.

angularjs
app.controller('UserCtrl', ['$routeParams', 'UserSvc',
  function($routeParams, UserSvc) {
    // URL /users/42  ->  $routeParams.id === '42' (always a string)
    this.user = UserSvc.get($routeParams.id);
  }]);

<!-- links -->
<a href="#!/users/42">View user 42</a>
<!-- with HTML5 mode, use a plain href="/users/42" -->

ngRoute 생명주기 이벤트

ngRoute는 $routeChangeStart(event.preventDefault로 취소 가능), $routeChangeSuccess, $routeChangeError를 브로드캐스트합니다. 'next'/'current' 인자가 라우트 설정(resolve 결과 포함)을 전달합니다. 인증 가드, 로딩 표시기, 브레드크럼 제목에 사용하세요. resolve 거부는 $routeChangeError를 발생시킵니다.

angularjs
app.run(['$rootScope', function($rootScope) {
  $rootScope.$on('$routeChangeStart', function(event, next, current) {
    if (next.requireAuth && !AuthService.isLoggedIn()) {
      event.preventDefault();             // cancel navigation
    }
  });

  $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
    $rootScope.pageTitle = current.$$route.title;
  });

  $rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {
    console.error('route failed', rejection);
  });
}]);

ui-router 상태

ui-router는 앱을 이름 있는 상태로 조직화합니다(URL 경로가 아님). ui-sref는 상태 이름과 파라미터로 링크하고, ui-view가 outlet입니다. 상태는 중첩될 수 있고 자체 URL을 가집니다. 내비게이션을 URL에서 분리하고 다중/명명된 뷰를 지원합니다 — 실제 앱에서 ngRoute보다 훨씬 강력합니다.

angularjs
var app = angular.module('myApp', ['ui.router']);

app.config(['$stateProvider', function($stateProvider) {
  $stateProvider
    .state('home', { url: '/home', templateUrl: 'home.html' })
    .state('users', { url: '/users', templateUrl: 'users.html' })
    .state('users.detail', {
      url: '/:id',
      templateUrl: 'user-detail.html',
      controller: 'UserDetailCtrl'
    });
}]);

<!-- outlet -->
<div ui-view></div>
<!-- links: state name instead of URL -->
<a ui-sref="users.detail({ id: 42 })">User 42</a>

ui-router resolve와 중첩 상태

resolve는 키를 프로미스에 매핑하며, 모두 resolve되기 전까지 컨트롤러가 인스턴스화되지 않습니다. resolve가 거부되면 $stateChangeError가 발생하고 상태에 진입하지 않습니다. resolve 값은 컨트롤러에 키로 주입됩니다. 자식 상태는 부모 resolve를 상속하고 접근할 수 있습니다 — 데이터 프리로딩에 유용합니다.

angularjs
$stateProvider.state('users.detail', {
  url: '/:id',
  templateUrl: 'user-detail.html',
  controller: 'UserDetailCtrl',
  controllerAs: 'vm',
  resolve: {
    // injected into the controller; waits for these before activating
    user: ['UserSvc', '$stateParams', function(UserSvc, $stateParams) {
      return UserSvc.get($stateParams.id);   // returns a promise
    }]
  }
});

app.controller('UserDetailCtrl', ['user', function(user) {
  this.user = user;   // already resolved
}]);

ui-router 다중 명명 뷰

ui-router는 상태당 여러 명명 ui-view outlet을 렌더링할 수 있습니다. views 맵의 키가 템플릿의 ui-view 이름과 일치하고, 빈 문자열 키는 이름 없는 outlet을 대상으로 합니다. 하나의 상태가 여러 영역(헤더, 사이드바, 메인)을 구성할 수 있습니다 — ngRoute의 단일 ng-view로는 불가능합니다.

angularjs
$stateProvider.state('dashboard', {
  url: '/dashboard',
  views: {
    '':        { templateUrl: 'dashboard/main.html' },
    'sidebar': { templateUrl: 'dashboard/sidebar.html', controller: 'SideCtrl' },
    'header':  { templateUrl: 'dashboard/header.html' }
  }
});

<!-- index.html -->
<div ui-view="header"></div>
<div ui-view="sidebar"></div>
<div ui-view></div>          <!-- the unnamed '' view -->
12

폼과 유효성 검사

ng-model을 사용한 폼

폼에 name 속성을 주면 스코프에 유효성 검사 상태가 노출됩니다. novalidate는 브라우저 내장 풍선을 꺼 Angular가 유효성 검사를 제어하게 합니다. 이름이 있는 input마다 자체 상태(myForm.email.$valid, $dirty, $error)를 게시합니다. 유효성 검사 추적을 위해서는 ng-model이 필요합니다.

angularjs
<form name="myForm" novalidate>
  <input name="email" type="email" ng-model="user.email" required>
  <input name="age" type="number" ng-model="user.age" min="18" required>

  <button ng-disabled="myForm.$invalid" ng-click="save()">Save</button>
</form>

<!-- novalidate disables the browser's native validation so Angular handles it -->

유효성 검사 상태

각 input은 $pristine/$dirty(변경 여부), $touched/$untouched(블러 여부), $valid/$invalid, $error(실패한 밸리데이터 맵)를 노출합니다. 폼이 이를 집계합니다: 입력 중 하나라도 유효하지 않으면 myForm.$invalid가 true입니다. 사용자가 입력하기 전에 잔소리하지 않도록 $touched 또는 $dirty 이후에만 메시지를 보여 주세요.

angularjs
<input name="email" ng-model="user.email" required>
<p ng-show="myForm.email.$touched && myForm.email.$error.required">
  Email is required.
</p>

<!-- states available on each input / the form -->
<!-- $pristine, $dirty, $touched, $untouched, $valid, $invalid, $error -->

내장 밸리데이터

내장 밸리데이터: required, type=email/url/number, min/max, ng-minlength/ng-maxlength, ng-pattern. 실패한 밸리데이터마다 $error에 키가 설정됩니다(예: $error.required, $error.minlength, $error.pattern). HTML 속성 안의 ng-pattern 정규식에서는 백슬래시를 이스케이프하세요.

angularjs
<input name="email" type="email" ng-model="user.email" required>
<input name="age" type="number" ng-model="user.age" min="18" max="120">
<input name="code" ng-model="user.code"
       ng-minlength="4" ng-maxlength="8" required>
<input name="url" type="url" ng-model="user.url">
<input name="zip" ng-model="user.zip" ng-pattern="/^\d{5}$/">

커스텀 밸리데이터 (디렉티브)

ngModel을 require하는 디렉티브로 ctrl.$validators에 함수를 등록해 커스텀 밸리데이터를 추가합니다. 유효하면 true, 아니면 false를 반환하면 $error의 여러분의 키(여기서는 'even') 아래 실패가 기록됩니다. 비동기 유효성 검사는 프로미스를 반환하는 ctrl.$asyncValidators를 사용합니다.

angularjs
app.directive('evenNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attrs, ctrl) {
      ctrl.$validators.even = function(modelValue, viewValue) {
        if (ctrl.$isEmpty(modelValue)) return true;   // let 'required' handle empty
        return parseInt(modelValue, 10) % 2 === 0;
      };
    }
  };
});

<input ng-model="n" even-number>
<p ng-show="form.n.$error.even">Must be even!</p>

ngMessages

ngMessages는 첫 번째로 매칭된 오류를 보여 줍니다(ng-messages-multiple로 전체 표시). 밸리데이터마다 ng-if를 쌓는 것보다 훨씬 깔끔합니다. 공통 메시지는 파셜로 빼서 ng-messages-include='messages.html'로 포함하세요. 내장 및 커스텀 밸리데이터 키 모두와 잘 동작합니다.

angularjs
<!-- include angular-messages.js, add module 'ngMessages' -->
<script src="angular-messages.js"></script>

<div ng-messages="myForm.email.$error" ng-if="myForm.email.$touched">
  <div ng-message="required">Email is required.</div>
  <div ng-message="email">Enter a valid email.</div>
  <div ng-message="server">That email is taken.</div>
</div>

<!-- a template can be reused across fields with ng-messages-include -->

폼 제출

ng-submit은 폼이 제출되면(Enter 키 또는 type='submit' 버튼) 발생하며, 재정의하지 않는 한 ng-model 유효성 검사가 통과할 때만 발생합니다. 안전 확인으로 핸들러에 myForm.$valid를 전달하세요. novalidate는 브라우저가 아닌 Angular가 유효성 검사를 주도하게 합니다. 중복 제출 방지는 ng-disabled로 버튼을 비활성화하세요.

angularjs
<form name="myForm" ng-submit="save(myForm.$valid)" novalidate>
  <input name="email" ng-model="user.email" required>
  <button type="submit" ng-disabled="myForm.$invalid">Save</button>
</form>

app.controller('FormCtrl', ['$scope', function($scope) {
  $scope.save = function(isValid) {
    if (!isValid) return;
    // ...submit to server
  };
}]);
13

이벤트 (ng-click, ng-change, ...)

ng-click

ng-click은 엘리먼트가 클릭되면 표현식을 평가합니다. $event는 네이티브 DOM 이벤트이므로 stopPropagation/preventDefault를 호출할 수 있습니다 — 하지만 폼에는 ng-submit을, 가능하면 내장 디렉티브를 선호하세요. ng-click은 버튼뿐 아니라 모든 엘리먼트에서 동작합니다.

angularjs
<button ng-click="count = count + 1">Inc</button>
<span>{{ count }}</span>

<!-- call a scope method -->
<button ng-click="save()">Save</button>

<!-- pass the native event with $event -->
<button ng-click="save($event)">Save</button>
<button ng-click="save($event); $event.stopPropagation()">Save</button>

ng-change

ng-change는 ng-model이 모델을 업데이트한 후 발생합니다 — 그래서 $scope.country는 이미 새 값입니다. 같은 엘리먼트에 ng-model이 필요합니다. 자체 change 리스너를 만들지 않고 input/select/checkbox 변경에 반응할 때(연쇄 드롭다운, 실시간 필터링) 사용합니다.

angularjs
<select ng-model="country" ng-change="onCountryChange()">
  <option value="us">US</option>
  <option value="uk">UK</option>
</select>

app.controller('LocCtrl', ['$scope', function($scope) {
  $scope.onCountryChange = function() {
    // fires AFTER ng-model updates $scope.country
    $scope.cities = CityService.forCountry($scope.country);
  };
}]);

ng-submit과 ng-focus/blur 계열

ng-submit은 폼 제출을 처리합니다. Angular는 많은 DOM 이벤트용 디렉티브도 노출합니다: ng-focus, ng-blur, ng-change, ng-copy, ng-cut, ng-paste, ng-keydown/up/press, ng-mousedown/up/enter/over/leave/move, ng-dblclick. 각각 표현식을 평가하며 $event를 사용할 수 있습니다.

angularjs
<!-- ng-submit: on form submission -->
<form ng-submit="search()">
  <input ng-model="query">
</form>

<!-- the ng-focus / ng-blur / ng-copy / ng-cut / ng-paste directives -->
<input ng-model="q" ng-focus="onFocus()" ng-blur="onBlur()">
<input ng-copy="copied = true">

키보드와 마우스 이벤트

Angular는 ng-keydown/ng-keypress/ng-keyup, ng-mousedown/up/enter/leave/over/move, ng-dblclick을 제공합니다. 각각 $event를 전달하므로 $event.keyCode나 $event.shiftKey를 검사할 수 있습니다. 앱 전역 단축키는 템플릿에 핸들러를 흩뿌리기보다 서비스 안에서 $document나 $window에 바인딩하세요.

angularjs
<!-- keyboard events -->
<input ng-keydown="onKey($event)">
<input ng-keypress="onKey($event)">

<!-- mouse events -->
<div ng-mouseenter="hover = true" ng-mouseleave="hover = false">
  {{ hover ? 'Hovering' : 'Not hovering' }}
</div>
<button ng-dblclick="open()">Double-click</button>

$event 객체

$event는 핸들러에 전달되는 네이티브 DOM 이벤트입니다. target, 좌표, 수정자 키를 읽고 preventDefault/stopPropagation을 호출할 수 있습니다. 클릭 핸들러에 무거운 로직을 넣지 마세요 — 컨트롤러/서비스의 메서드를 호출하세요. $event는 모든 이벤트 디렉티브에서 사용할 수 있습니다.

angularjs
<button ng-click="onClick($event)">Click</button>

app.controller('ClickCtrl', ['$scope', function($scope) {
  $scope.onClick = function(event) {
    console.log(event.target);    // clicked element
    console.log(event.clientX, event.clientY);
    event.preventDefault();
    event.stopPropagation();
  };
}]);

이벤트 수식어 (수동)

Vue/Angular 2+와 달리 AngularJS에는 .stop/.prevent/.once 수식어가 없습니다 — 핸들러 안에서 직접 이벤트 메서드를 호출해야 합니다. 더 장황하지만 명시적입니다. 자주 필요한 동작(제출 시 자동 preventDefault)은 ng-submit이 폼에서 이미 처리해 줍니다.

angularjs
<!-- AngularJS has NO built-in modifiers like .stop / .prevent.
     Call the method on $event instead. -->
<a href="/delete" ng-click="del($event)">Delete</a>

app.controller('DelCtrl', ['$scope', function($scope) {
  $scope.del = function(event) {
    event.preventDefault();   // stop the link navigation
    $scope.removeItem();
  };
}]);
14

$watch / $digest / $apply

$scope.$watch

$watch는 digest 중 감시 대상 값이 바뀔 때마다 실행되는 리스너를 등록합니다. 첫 번째 인자는 문자열 표현식이나 함수이며, 콜백은 (newVal, oldVal)을 받습니다. $watch는 해제 함수를 반환합니다 — 감시를 멈추고 누수를 피하려면 호출하세요. 특히 디렉티브에서 중요합니다.

angularjs
app.controller('WatchCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' };

  // watch a path expression (string)
  var unbind = $scope.$watch('user.name', function(newVal, oldVal) {
    console.log('name changed', oldVal, '->', newVal);
  });

  // stop watching (frees resources)
  unbind();
}]);

$watchCollection

$watchCollection은 배열이나 객체의 한 단계를 감시합니다: 항목이 추가/제거/교체될 때 발생하지만 항목 프로퍼티를 깊이 비교하지는 않습니다. 깊은 $watch(세 번째 인자 true)보다 훨씬 저렴합니다. 원시값 배열이나 목록 구성원만 관심 있을 때 사용하세요.

angularjs
$scope.items = [1, 2, 3];

// watch array/object shallowly: detects add/remove/replace but NOT deep mutation
$scope.$watchCollection('items', function(newItems, oldItems) {
  console.log('collection changed', newItems);
});

// fires on push/splice, or when an item is replaced,
// but NOT when an item's own properties change.

깊은 $watch (세 번째 인자)

세 번째 인자로 true를 전달하면 $watch가 깊은 값 비교를 합니다 — 중첩된 프로퍼티가 바뀌어도 발생합니다. 비용이 큽니다(매 digest마다 객체 전체를 순회). 특정 경로 감시나 $watchCollection을 선호하세요. 깊은 감시는 정말 필요한 작은 객체에만 아껴 쓰세요.

angularjs
$scope.config = { ui: { theme: 'dark' } };

// third arg true -> deep comparison by value (expensive!)
$scope.$watch('config', function(n, o) {
  console.log('config (deep) changed');
}, true);

// prefer watching a specific path when possible:
$scope.$watch('config.ui.theme', function(n, o) { /* cheaper */ });

$scope.$apply

Angular의 세계 밖의 코드(순수 setTimeout, $http 없는 XHR, jQuery 이벤트, Promise 콜백)는 모델을 업데이트하지만 Angular가 모릅니다 — $apply()를 호출해 $digest를 트리거하세요. 함수 형태는 변경을 감싸 예외를 처리하고 단일 digest를 실행합니다. Angular 서비스($http, $timeout) 내부에서는 $apply가 이미 되어 있으니 중복 적용하지 마세요.

angularjs
// NON-Angular async callback (e.g., a 3rd-party library) won't trigger a digest
externalLib.onReady(function() {
  $scope.message = 'Ready!';

  // tell Angular to run a digest so the view updates
  $scope.$apply();
});

// or wrap the change so errors are caught and digest runs once
$scope.$apply(function() {
  $scope.message = 'Ready!';
  $scope.ready = true;
});

$evalAsync와 $timeout (안전한 apply)

digest가 이미 진행 중인지 확실하지 않다면 수동 $apply 대신 $evalAsync나 $timeout(fn, 0)을 선호하세요 — 'digest already in progress' 오류를 피합니다. $evalAsync는 현재 digest에 배치하고, $timeout은 다음 틱으로 미룹니다. DOM이 렌더링된 상태가 필요하면 $timeout을 사용하세요.

angularjs
// $evalAsync: schedule work later in the SAME digest if one is running,
//             otherwise start a new one. Safer than $apply.
$scope.$evalAsync(function() {
  $scope.computed = heavyCompute();
});

// $timeout(..., 0) always runs in a fresh digest — useful when you
// need the DOM updated before your code runs.
$timeout(function() {
  $scope.deferred = true;
}, 0);

$digest 사이클 이해

$digest는 모델 변경을 뷰로 전파하는 루프입니다: 값이 더 이상 바뀌지 않을 때까지(더티 체킹) 모든 watcher를 재평가하며 최대 10번 반복합니다. 모든 watcher가 매 digest마다 실행되므로 성능은 watcher 수에 비례합니다. 일회성 바인딩(::), track by, 계산의 컨트롤러 이동으로 watcher 수를 줄이세요.

angularjs
// a $digest iterates over ALL watchers on $scope and its children:
//   1. read each watched value, compare to previous
//   2. if changed, call the listener
//   3. listeners may change other watched values -> re-run
//   4. repeat until stable (max 10 iterations -> error)

// so: keep watchers cheap and few.
// track by, one-time binding (::), and compute in controllers help.
15

컴포넌트 (.component())

.component() 기본

.component()는 directive의 문법적 설탕으로, 템플릿 기반 컴포넌트에 최적화되어 있습니다. restrict 'E', isolate 스코프, controllerAs '$ctrl'이 기본입니다 — $scope 대신 this($ctrl 별칭)를 사용하세요. bindings가 scope:{...}를 대체하며, 1.5부터 input에는 '='보다 '<'(단방향 입력)가 권장됩니다.

angularjs
app.component('heroDetail', {
  template: '<h2>{{$ctrl.hero.name}}</h2><p>{{$ctrl.hero.power}}</p>',
  bindings: {
    hero: '<'        // one-way ('<'), two-way ('='), string ('@'), expr ('&')
  }
});

<!-- usage -->
<hero-detail hero="selectedHero"></hero-detail>

컨트롤러와 바인딩을 가진 컴포넌트

컴포넌트의 컨트롤러는 this를 사용합니다(템플릿에서 $ctrl 별칭). bindings는 input('<', '=')과 output('&')을 선언합니다. input에는 단방향 '<'가 권장됩니다. output은 '&'를 사용하며 — 부모 표현식의 locals가 되는 인자 객체로 호출합니다: onChange({ value: ... }).

angularjs
app.component('counter', {
  bindings: {
    start: '<',
    onChange: '&'
  },
  template: `
    <button ng-click="$ctrl.dec()">-</button>
    <span>{{ $ctrl.count }}</span>
    <button ng-click="$ctrl.inc()">+</button>
  `,
  controller: function() {
    this.$onInit = function() { this.count = this.start || 0; };
    this.inc = function() { this.count++; this.onChange({ value: this.count }); };
    this.dec = function() { this.count--; this.onChange({ value: this.count }); };
  }
});

컴포넌트 생명주기 훅

AngularJS 1.5+ 컴포넌트 훅은 Angular 2+의 생명주기를 미러링합니다: $onInit(초기화), $onChanges(바인딩 변경, isFirstChange 포함), $doCheck(매 digest), $postLink(자식 DOM 링크 후), $onDestroy(해체). 생성자에 로직을 붙이는 대신 사용하세요 — 컴포넌트 동작이 명시적이고 테스트 가능해 집니다.

angularjs
app.component('editor', {
  bindings: { doc: '<', onClose: '&' },
  controller: function() {
    this.$onInit = function() { /* after bindings, before first render */ };
    this.$onChanges = function(changes) {
      // changes.doc: { currentValue, previousValue, isFirstChange() }
    };
    this.$doCheck = function() { /* every digest: custom dirty checking */ };
    this.$onDestroy = function() { /* cleanup: timers, listeners */ };
    this.$postLink = function() { /* after child linking, DOM ready */ };
  }
});

$onChanges 상세

$onChanges는 단방향('<') 바인딩의 참조가 바뀔 때마다 발생하며 changes 객체를 받습니다: 각 키에 currentValue, previousValue, isFirstChange()가 있습니다. 같은 객체의 변형에는 발생하지 않습니다(참조가 같으므로) — 그건 $doCheck를 사용하세요. 초기화 시 isFirstChange()가 true로 한 번은 항상 발생합니다.

angularjs
app.component('userView', {
  bindings: { user: '<' },
  controller: function() {
    this.$onChanges = function(changesObj) {
      // changesObj is keyed by binding name
      if (changesObj.user) {
        var c = changesObj.user;
        console.log(c.previousValue, '->', c.currentValue);
        console.log('first time?', c.isFirstChange());
      }
    };
  }
});

컴포넌트의 트랜스클루전

transclude: true를 설정하고 템플릿에 ng-transclude를 넣으면 호출자가 콘텐츠를 주입할 수 있습니다. 컴포넌트에서는 transclude: { slotName: 'elementName' }으로 멀티 슬롯 트랜스클루전도 지원합니다. 트랜스클루전으로 본문을 부모가 채우는 재사용 가능한 래퍼(패널, 모달, 카드)를 만들 수 있습니다.

angularjs
app.component('modal', {
  transclude: true,
  template: `
    <div class="modal">
      <div class="modal-body" ng-transclude></div>
    </div>
  `,
  bindings: { title: '@' }
});

<!-- caller's content lands in ng-transclude -->
<modal title="Confirm">
  <p>Are you sure?</p>
  <button>Yes</button>
</modal>

컴포넌트 vs 디렉티브

템플릿을 렌더링하는 모든 것에는 컴포넌트를 사용하세요 — 더 단순하고 Angular 2+ 모델(isolate 스코프, this/controllerAs, 생명주기 훅)로 이끕니다. 디렉티브는 템플릿 없는 어트리뷰트 스타일 동작(autofocus, 툴팁 트리거, input mask)과 link에서의 직접 DOM 조작을 위해 남겨 두세요.

angularjs
// COMPONENT: template-based, isolate scope, controllerAs by default
app.component('userCard', {
  template: '...',
  bindings: { user: '<' }
});

// DIRECTIVE: still needed for attribute behavior / DOM manipulation
app.directive('autoFocus', function() {
  return { restrict: 'A', link: function(scope, el) { el[0].focus(); } };
});
16

$q 프로미스 서비스

$q.defer() 기본

$q는 Angular의 Promise 구현입니다(Promises/A+). $q.defer()로 만들고 resolve(value) 또는 reject(reason)를 호출합니다. 프로미스는 digest를 인식합니다: 해결 시 $digest가 트리거되어 뷰가 갱신됩니다. Angular의 자동 digest가 필요하면 네이티브 Promise보다 $q를 선호하고, 아니면 네이티브 Promise도 됩니다.

angularjs
app.factory('AsyncWork', ['$q', function($q) {
  return function() {
    var deferred = $q.defer();

    setTimeout(function() {
      if (success) deferred.resolve('done');
      else         deferred.reject(new Error('failed'));
    }, 100);

    return deferred.promise;     // { then, catch, finally }
  };
}]);

// consume
AsyncWork().then(function(v) { console.log(v); })
          .catch(function(e) { console.error(e); });

$q.when / $q.all / $q.reject

$q.when은 일반 값이나 $q가 아닌 프로미스를 감쌉니다. $q.all은 프로미스의 배열이나 객체를 기다려 같은 모양의 결과로 이행합니다. $q.reject(reason)는 거부된 프로미스를 반환하는 편리한 방법입니다(예: 체인의 조기 유효성 검사). 모두 digest를 인식합니다.

angularjs
// $q.when: wrap a value (or foreign promise) in an Angular promise
$q.when(42).then(function(v) { /* v === 42 */ });

// $q.all: wait for many promises in parallel
$q.all([getUser(), getPosts(), getFriends()]).then(function(results) {
  var user = results[0], posts = results[1], friends = results[2];
});

// $q.all with an object (named results)
$q.all({ user: getUser(), posts: getPosts() }).then(function(r) {
  r.user; r.posts;
});

// $q.reject: shortcut to return a rejected promise
return $q.reject(new Error('bad input'));

프로미스 체이닝

.then에서 값을 반환하면 다음 핸들러로 전달되고, 프로미스를 반환하면 체인이 기다립니다. 하나의 .catch가 업스트림의 모든 거부를 처리합니다. .finally는 성공과 실패 모두에서 실행됩니다 — 로더 숨기기에 완벽합니다. 각 핸들러는 Angular의 digest 안에서 실행되므로 스코프 업데이트가 자연스럽게 동작합니다.

angularjs
getUser(id)
  .then(function(user) {
    return getOrders(user);    // return a promise -> chain waits
  })
  .then(function(orders) {
    return orders.filter(paid); // return a value -> next step
  })
  .then(function(paidOrders) {
    $scope.paid = paidOrders;
  })
  .catch(function(err) {
    // any rejection above lands here
    console.error(err);
  })
  .finally(function() {
    $scope.loading = false;    // runs regardless
  });

$http는 프로미스를 반환

$http는 이미 $q 프로미스를 반환하므로 .then으로 응답을 변환하고(보통 .data 추출) 더 깔끔한 값을 반환하세요. $http를 서비스로 감싸면 호출자에게 깔끔한 API를 주고 URL/기본 URL/오류 처리를 중앙화합니다. 인터셉터도 $http의 횡단 동작을 적용하는 방법입니다.

angularjs
app.factory('UserApi', ['$http', function($http) {
  return {
    list: function() { return $http.get('/users').then(function(r) { return r.data; }); },
    get:  function(id) { return $http.get('/users/' + id).then(function(r) { return r.data; }); }
  };
}]);

// caller doesn't deal with response.data, just the user
UserApi.get(42).then(function(user) { $scope.user = user; });

$q 생성자 (ES6 스타일)

1.6부터 $q는 ES6 Promise 생성자 형태를 지원합니다: $q(function(resolve, reject){...}). $q.defer()보다 간결하고 네이티브 Promise 문법과 일치합니다. 단일 비동기 API를 감쌀 때 사용하세요. 결과 프로미스는 여전히 digest를 인식하므로 resolve 시 뷰 업데이트가 자동 발생합니다.

angularjs
// Angular 1.6+ supports the resolver-style constructor, like native Promise
app.factory('loadImg', ['$q', function($q) {
  return function(src) {
    return $q(function(resolve, reject) {
      var img = new Image();
      img.onload  = function() { resolve(img); };
      img.onerror = function() { reject(new Error('load failed')); };
      img.src = src;
    });
  };
}]);

$q vs 네이티브 Promise

핵심 차이: $q는 해결 시 $digest를 트리거하고 네이티브 Promise는 그렇지 않습니다. 에버그린 브라우저에서 돌아가는 모던 AngularJS 앱에서는 네이티브 Promise를 쓸 수 있지만 모델 업데이트를 $apply(또는 $evalAsync)로 감싸야 합니다. 일관성과 편의를 위해 Angular 코드 안에서는 $q를 선호하세요.

angularjs
// native Promise: no auto-digest; you must $apply manually
Promise.resolve().then(function() {
  $scope.x = 1;
  $scope.$apply();           // otherwise the view won't update
});

// $q promise: resolves inside a $digest automatically
$q.when().then(function() { $scope.x = 1; });   // view updates
17

애니메이션 (ngAnimate)

ngAnimate 설정

ngAnimate는 별도 모듈입니다(자체 JS 파일). 의존성으로 추가하면 내장 디렉티브가 자동으로 확장되어 enter/leave/move 전환 중 CSS 클래스를 추가합니다 — CSS만 작성하면 됩니다. 흔한 경우 JS가 필요 없습니다. ngAnimate가 없으면 이 디렉티브들은 DOM을 즉시 변경합니다.

angularjs
<!-- include angular-animate.js, then depend on 'ngAnimate' -->
<script src="angular-animate.js"></script>

var app = angular.module('myApp', ['ngAnimate']);

<!-- ngAnimate now adds classes automatically to:
     ng-repeat (enter/leave/move), ng-if, ng-show, ng-hide,
     ng-class, ng-view, ng-include, ui-view -->

CSS 트랜지션 클래스

ngAnimate는 이벤트마다 두 클래스를 추가합니다: 시작 클래스(예: .ng-enter)와 한 프레임 뒤의 -active 클래스(.ng-enter-active). 시작 클래스에 CSS 트랜지션을 정의하고 active 클래스에 최종 상태를 정의하세요 — 트랜지션이 끝나면 Angular가 둘 다 제거합니다. 가장 단순하고 성능 좋은 애니메이션 방식입니다.

angularjs
/* .ng-enter / .ng-leave / .ng-move are added automatically */
.fade.ng-enter        { transition: opacity 0.3s; opacity: 0; }
.fade.ng-enter-active { opacity: 1; }

.fade.ng-leave        { transition: opacity 0.3s; opacity: 1; }
.fade.ng-leave-active { opacity: 0; }

<!-- apply the .fade class to your ng-if / ng-repeat element -->
<div class="fade" ng-if="show">Hello</div>

CSS 키프레임 애니메이션

트랜지션 대신 CSS @keyframes 애니메이션을 사용할 수 있습니다 — ngAnimate가 같은 .ng-enter/.ng-leave/.ng-move 클래스를 토글하고 키프레임이 실행됩니다. 키프레임에서는 애니메이션이 전체 시퀀스를 주도하므로 시작 클래스 하나만 필요합니다(-active 불필요). 바운스/스프링 효과에 좋습니다.

angularjs
/* use @keyframes; ngAnimate still toggles the classes */
.pop.ng-enter { animation: pop-in 0.3s; }

@keyframes pop-in {
  0%   { transform: scale(0); }
  100% { transform: scale(1); }
}

<div class="pop" ng-if="visible">Pop!</div>

ng-repeat enter / leave / move

ng-repeat 항목은 .ng-enter(새 항목), .ng-leave(제거됨), .ng-move(재정렬됨) 클래스를 받습니다. Angular가 변경 사이에서 항목을 매칭하고 move를 올바르게 애니메이션하도록 track by를 사용하세요. .ng-enter-stagger / .ng-leave-stagger로 항목마다 지연을 주는 스태거 애니메이션도 가능합니다 — 목록 공개 효과에 좋습니다.

angularjs
/* list items animate when added, removed, or reordered */
.list-item.ng-enter        { transition: all 0.3s; opacity: 0; transform: translateY(-10px); }
.list-item.ng-enter-active { opacity: 1; transform: translateY(0); }

.list-item.ng-leave-active { opacity: 0; transform: translateX(20px); }

/* .ng-move animates reordering (track by recommended) */
.list-item.ng-move        { transition: transform 0.3s; }
.list-item.ng-move-active { }

<ul><li class="list-item" ng-repeat="t in todos track by t.id">{{ t.text }}</li></ul>

$animate 서비스 (JS 애니메이션)

app.animation(cssSelector, factory)는 셀렉터에 매칭되는 엘리먼트의 JS 애니메이션을 등록합니다. enter/leave/move/class 메서드는 엘리먼트와 done 콜백을 받습니다. CSS만으로 부족할 때(예: jQuery.animate나 물리 라이브러리) 유용합니다. 정리를 위해 cancel 함수를 반환하세요. JS 애니메이션은 CSS보다 무겁습니다 — 가능하면 CSS를 선호하세요.

angularjs
app.animation('.fade-js', ['$animate', function($animate) {
  return {
    enter: function(element, done) {
      element.css('opacity', 0);
      element.animate({ opacity: 1 }, 300, done);
      return function(cancelled) { /* cleanup if cancelled */ };
    },
    leave: function(element, done) {
      element.animate({ opacity: 0 }, 300, done);
    }
  };
}]);

<div class="fade-js" ng-if="show">Hello</div>

애니메이션 비활성화

$animate.enabled로 전역 또는 서브트리별로 애니메이션을 끄거나, ng-animate-disabled 클래스를 사용하세요. 큰 목록의 성능이나 테스트 중 애니메이션 비활성화에 유용합니다. ng-animate-children은 부모가 자식의 함께 애니메이션 되기를 선택하게 합니다(기본적으로 부모 애니메이션은 자식 애니메이션을 건너뜁니다).

angularjs
<!-- ng-animate-ref / ng-animate-sref control animation between routes -->

<!-- opt out per-element -->
<div ng-if="x" ng-animate-children>...</div>
<div ng-if="y" class="ng-animate-disabled">...</div>

// programmatically
$animate.enabled(false);                    // globally off
$animate.enabled(false, element);           // off for subtree
$animate.enabled(true, element);            // back on
18

테스팅 (Karma와 Jasmine)

Karma 설정 스케치

Karma는 AngularJS의 표준 테스트 러너입니다: 실제 브라우저를 띄우고, 스크립트와 angular-mocks를 로드하며, Jasmine 결과를 보고합니다. angular-mocks는 module()과 inject() 헬퍼와 목 서비스($httpBackend)를 제공합니다. singleRun:true은 한 번 실행 후 종료합니다(CI); 워치 모드에서는 생략하세요.

angularjs
// karma.conf.js (sketch)
module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'test/**/*.spec.js'
    ],
    browsers: ['ChromeHeadless'],
    singleRun: true
  });
};

// run: karma start karma.conf.js

Jasmine 기본

Jasmine은 describe(스위트), it(스펙), beforeEach/afterEach(설정/해체), 매처와 함께 expect(toBe, toEqual, toContain, toBeTruthy, toThrow 등)를 제공합니다. xit/xdescribe는 스펙을 건너뜁니다. 테스트는 기본적으로 동기이며, 비동기에는 done 콜백이나 Jasmine의 async/await 지원을 사용합니다.

angularjs
describe('UserService', function() {
  beforeEach(function() { /* setup */ });
  afterEach(function() { /* teardown */ });

  it('isLoggedIn is false by default', function() {
    var svc = makeService();
    expect(svc.isLoggedIn()).toBe(false);
  });

  it('greets by name', function() {
    expect(greet('Ada')).toEqual('Hi, Ada');
  });

  // pending / disabled
  xit('not yet implemented', function() {});
});

컨트롤러 테스팅

module('myApp')이 Angular 모듈을 로드하고, inject()가 서비스를 해결합니다(밑줄로 감싼 별칭으로 자주 받습니다). $controller('Name', { $scope: scope })로 가짜 의존성을 전달해 컨트롤러를 만듭니다. 그다음 스코프를 검증합니다. 이 패턴은 controllerAs에도 통합니다: this에 바인딩된 메서드를 전달하고 반환된 인스턴스를 검사하세요.

angularjs
describe('TodoCtrl', function() {
  beforeEach(module('myApp'));

  var $controller, $scope;
  beforeEach(inject(function(_$controller_, _$rootScope_) {
    $scope = _$rootScope_.$new();
    $controller = _$controller_;
  }));

  it('starts with two todos', function() {
    $controller('TodoCtrl', { $scope: $scope });
    expect($scope.todos.length).toBe(2);
  });

  it('addTodo pushes and clears the input', function() {
    $controller('TodoCtrl', { $scope: $scope });
    $scope.todoText = 'New';
    $scope.addTodo();
    expect($scope.todos.length).toBe(3);
    expect($scope.todoText).toBe('');
  });
});

서비스 테스팅

테스트 대상 서비스와 angular-mocks의 $httpBackend를 주입합니다. expectGET(url).respond(data)로 가짜 응답을 준비하고, flush()가 대기 중인 요청을 동기적으로 해결합니다. afterEach의 verifyNoOutstandingExpectation()이 미충족 기대를 잡아 냅니다. 실제 서버 없이 $http 기반 서비스를 완전히 테스트할 수 있습니다.

angularjs
describe('UserService', function() {
  var UserService, $httpBackend;

  beforeEach(module('myApp'));
  beforeEach(inject(function(_UserService_, _$httpBackend_) {
    UserService = _UserService_;
    $httpBackend = _$httpBackend_;
  }));

  afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); });

  it('list() fetches users', function() {
    $httpBackend.expectGET('/api/users').respond([{ name: 'Ada' }]);
    var users;
    UserService.list().then(function(u) { users = u; });
    $httpBackend.flush();          // resolve the pending request
    expect(users.length).toBe(1);
  });
});

디렉티브 테스팅

$compile(html)(scope)로 HTML 조각을 컴파일하고, scope.$digest()로 바인딩을 평가하고 디렉티브를 링크합니다. 결과 jqLite 엘리먼트를 검증합니다(el.find, el.text, el.attr). templateUrl은 $httpBackend.expectGET으로 템플릿을 제공하고 digest 전에 flush하세요. isolate 스코프는 el.isolateScope()로 테스트합니다.

angularjs
describe('greeting directive', function() {
  var $compile, $rootScope;
  beforeEach(module('myApp'));
  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_; $rootScope = _$rootScope_;
  }));

  it('renders the template', function() {
    var scope = $rootScope.$new();
    scope.name = 'Ada';
    var el = $compile('<greeting name="name"></greeting>')(scope);
    scope.$digest();              // process watchers / bindings
    expect(el.find('h1').text()).toContain('Ada');
  });
});

$httpBackend 목킹

expectGET(expectPOST 등)은 요청이 만들어졌음을 검증하며 없으면 실패합니다; whenGET은 호출되면 조용히 데이터를 반환하고 없으면 무시합니다. '이런 일이 있어야 한다'는 검증에는 expect, 설정에는 when을 사용하세요. flush()는 대기 중인 요청을 순서대로 해결합니다. 불일치를 잡으려면 afterEach에서 항상 verifyNoOutstanding*을 호출하세요.

angularjs
// EXPECT: a specific request must happen (asserts it was made)
$httpBackend.expectGET('/api/users').respond(200, [{ id: 1 }]);
// WHEN:  just stub a request if it happens (no assertion)
$httpBackend.whenGET('/api/users').respond(200, [{ id: 1 }]);

// flush triggers all pending requests:
$httpBackend.flush();

// verify nothing was left unflushed:
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
19

의존성 주입

DI 기본

Angular의 DI는 함수 파라미터 이름을 검사해 의존성을 해결합니다. 이 '암묵적' 스타일은 간결하지만 minification에서 깨집니다(파라미터 이름이 줄어듦). 프로토타입/데모에는 괜찮습니다. 프로덕션에서는 인라인 배열이나 $inject 같은 어노테이션 스타일을 쓰거나 ng-annotate로 자동화하세요.

angularjs
// services are injected by NAME into the constructor's parameters
app.controller('A', function($scope, $http, UserService) { /* ... */ });

// Angular inspects the parameter names to resolve dependencies.
// works in development but BREAKS after minification (see below).

인라인 배열 어노테이션

가장 흔한 minification 안전 스타일입니다: 서비스 이름(문자열)을 요소로 하는 배열을 전달하고 생성자를 마지막에 둡니다. 문자열은 minification에서 살아남아 Angular가 올바르게 해결합니다. minify될 코드에는 항상 이것을 사용하세요. 수동 유지가 번거로우니 ng-annotate나 babel 플러그인으로 자동 추가할 수 있습니다.

angularjs
app.controller('A', ['$scope', '$http', 'UserService',
  function($scope, $http, UserService) {
    // parameter names no longer matter; the strings drive DI
    $scope.users = UserService.list();
  }
]);

$inject 프로퍼티 어노테이션

생성자 함수에 서비스 이름 문자열의 $inject 배열을 붙입니다. Angular가 이를 읽어 의존성을 해결하며 파라미터 이름은 무시합니다. 함수 선언이 읽기 쉽게 유지되고 같은 생성자를 재사용할 수 있습니다. ng-annotate는 빌드 중 파라미터 이름에서 $inject를 자동 생성할 수 있습니다.

angularjs
function ACtrl($scope, UserService) {
  $scope.users = UserService.list();
}
ACtrl.$inject = ['$scope', 'UserService'];   // explicit list

app.controller('A', ACtrl);

// equivalent to the inline array form; useful when you want
// a separately-declared, reusable constructor function.

$injector 서비스

$injector는 DI 컨테이너입니다: .get(name)은 싱글턴을 반환하고, .annotate(fn)은 의존성 목록을 반환하며, .instantiate/.invoke는 의존성과 함께 함수를 생성/호출합니다. 앱 코드에서는 드물지만 이름으로 서비스를 로드하는 동적 시나리오, 커스텀 디렉티브나 라우터 resolve 내부에서 유용합니다.

angularjs
// resolve and instantiate on demand
var svc = $injector.get('UserService');          // retrieve singleton
var fn  = $injector.annotate(MyCtrl);            // [' $scope', ...] via reflection
var inst = $injector.instantiate(MyCtrl);        // 'new' with DI
var res  = $injector.invoke(MyCtrl, context);    // call with DI

// list all registered service names (debug)
// $injector has modules / providers info

ng-annotate (빌드 시)

ng-annotate는 빌드 시 인라인 배열 어노테이션을 자동 추가하는 도구입니다 — 암묵적 DI를 깔끔하게 쓰고 minification 안전 코드를 배포할 수 있습니다. 애매한 경우는 /* @ngInject */로 구분하세요. gulp, grunt, webpack, babel과 통합됩니다. 후속 프로젝트 ng-annotate-patched가 현대 툴체인 지원을 유지합니다.

angularjs
// Write clean code with a hint comment:
app.controller('A', /* @ngInject */ function($scope, UserService) {
  $scope.users = UserService.list();
});

// ng-annotate (run by your build tool) rewrites it to:
app.controller('A', ['$scope', 'UserService', function($scope, UserService) {
  $scope.users = UserService.list();
}]);

Strict DI 모드

ng-strict-di는 어노테이션 없는 암묵적 DI가 런타임에 예외를 던지게 합니다 — minification에 안전하지 않은 코드를 프로덕션이 아닌 개발 중에 잡을 수 있습니다. 개발과 테스트에서는 켜 두세요. 약간의 성능 영향(추가 검사)이 있어 프로덕션 빌드에서는 보통 제거됩니다.

angularjs
<html ng-app="myApp" ng-strict-di>
  ...
</html>

// or when bootstrapping manually:
angular.bootstrap(root, ['myApp'], { strictDi: true });

// in strict-DI mode, any service using IMPLICIT (unannotated) DI
// throws an error, catching minification bugs during development.
20

모범 사례와 성능

controllerAs 사용

controllerAs는 각 프로퍼티를 소유한 컨트롤러를 명확히 하고, 스코프 상속의 원시값 가림을 피하며, Angular 2+ '컴포넌트' 모델에 가깝게 만듭니다. $scope 대신 this(별칭)에 바인딩하세요. 컴포넌트에서는 $ctrl이 기본 별칭입니다 — 일관되게 사용하세요.

angularjs
<!-- prefer controllerAs over $scope -->
<div ng-controller="UsersCtrl as users">
  <li ng-repeat="u in users.list">{{ u.name }}</li>
</div>

app.controller('UsersCtrl', function(UserService) {
  // 'this' is exposed as 'users' in the template
  this.list = UserService.list();
  this.remove = function(id) { UserService.remove(id); };
});

일회성 바인딩 (::)

표현식 앞에 ::를 붙이면 일회성 바인딩이 됩니다: Angular가 한 번 평가하고 정의되면 watcher를 제거합니다. 바뀌지 않는 데이터(제목, 타임스탬프, 정적 목록)에는 watcher 수를 크게 줄여 줍니다 — AngularJS 앱에서 단일 최대 성능 승리입니다.

angularjs
<!-- static data: bind once, drop the watcher -->
<h1>{{ ::conference.name }}</h1>
<span>{{ ::user.createdAt | date }}</span>

<!-- ng-repeat over a static list -->
<li ng-repeat="item in ::staticItems">{{ item.label }}</li>

<!-- less watchers = faster digest for the whole app -->

ng-repeat의 track by

track by가 없으면 Angular는 내부 $$hashKey로 항목을 매칭합니다 — 배열이 바뀌면 실제로 바뀌지 않은 항목의 DOM을 재렌더링/재생성해 자식 상태를 잃을 수 있습니다. track by u.id가 안정적인 식별자를 주어 Angular가 노드를 재사용합니다. 큰 목록 성능에 필수이며 'ng-repeat 중복' 오류도 고칩니다.

angularjs
<!-- BAD: Angular uses $$hashKey, re-renders everything on change -->
<li ng-repeat="u in users">{{ u.name }}</li>

<!-- GOOD: stable identity -> Angular reuses DOM nodes -->
<li ng-repeat="u in users track by u.id">{{ u.name }}</li>

<!-- for primitives, use $index (only if list doesn't reorder) -->
<li ng-repeat="n in nums track by $index">{{ n }}</li>

로직을 서비스로 이동

컨트롤러는 테스트가 어렵고 $scope에 묶입니다; 서비스는 싱글턴이고 주입 가능하며 단위 테스트 가능합니다. 비즈니스 로직, 데이터 접근, 공유 상태를 서비스로 밀어 넣고, 컨트롤러는 뷰를 그 서비스에 연결하는 데 집중하세요. 이 분리로 여러 컨트롤러가 같은 로직을 공유할 수도 있습니다.

angularjs
// BAD: logic crammed in the controller
app.controller('BadCtrl', function($scope) {
  $scope.calc = function() { /* 50 lines of business logic */ };
});

// GOOD: controller delegates to a testable service
app.controller('GoodCtrl', function(PriceService) {
  this.total = PriceService.calcTotal(this.items);   // thin
});

app.factory('PriceService', function() {
  return { calcTotal: function(items) { /* ... */ } };
});

Bind Once / watcher 수 줄이기

모든 {{ }}과 대부분의 바인딩은 매 digest마다 실행되는 watcher를 추가합니다. 바인딩 안의 함수 호출을 피하세요(입력이 같아도 매 digest 다시 실행됨) — 미리 계산해 결과를 저장하세요. 일회성 바인딩(::), track by, 컨트롤러 측 계산을 조합해 큰 페이지에서 watcher 수를 낮게 유지하세요.

angularjs
<!-- compute once in the controller, render many times -->
app.controller('Ctrl', function() {
  this.sortedUsers = this.users.slice().sort(byName); // do it once
});

<!-- avoid function calls in bindings: they re-run each digest -->
<!-- BAD:  {{ heavyCompute() }} -->
<!-- GOOD: compute once, bind the result -->
<p>{{ cachedResult }}</p>

모듈 조직화

파일 타입이 아닌 기능별로 조직화하세요 — 각 기능이 자체 컨트롤러, 서비스, 템플릿, 라우트, 테스트를 갖는 자기 완결적 모듈이 됩니다. 루트 앱 모듈은 기능 모듈을 조합하기만 합니다. 관련 코드가 함께 모이고, 기능을 앱 간에 재사용할 수 있으며, 단일 거대 모듈보다 훨씬 잘 확장됩니다.

angularjs
// split features into sub-modules, each self-contained
angular.module('myApp.users', ['myApp.common']);
angular.module('myApp.posts', ['myApp.common']);
angular.module('myApp', ['myApp.users', 'myApp.posts', 'ngRoute']);

// file layout per feature:
//   users/users.module.js
//   users/users.controller.js
//   users/users.service.js
//   users/users.html
//   users/users.routes.js
//   users/users.spec.js

Was this helpful?