2. Expressions (번역)
AngularJS Expressions 와 Javascript Expressions 차이점
AngularJS Expressions은 Javascript와 비슷하긴 하지만 차이점이 있습니다.
- Context : Javascript 에서 Expressions 는 global window 객체에서 연산되지만, Angular JS는 scope 라는 object에서 연산됩니다.
- Forgiving : Javascript 에서는 undefined 프로퍼티를 연산하려고 했을 때, ReferenceError , TypeError가 발생하지만, AngularJS는 undefined를 null 취급합니다.
- Filters : Expression 내에 data display 전 filters를 사용할 수 있습니다.
- No Control Flow Statements : AngularJS Expression 에서는 conditonal, loops, exception 을 사용하지 않습니다.
- No Function Declarations : AngularJS Expression 내에서 함수를 선언할 수 없습니다. (ng-init 도 예외는 아닙니다.)
- No RegExp Creation With Literal Notation : AngularJS Expression 내에서 정규식을 사용할 수 없습니다. 대신 ng-pattern 을 사용합니다.
- No Object Creation With New Operator : AngularJS 에서 new Operator를 사용할 수 없습니다.
- No Bitwise, Comma, And Void Operators : AngularJS 에서 Bitwise , ',' , void operator를 사용할 수 없습니다.
Example
See the Pen Expression Example by jjh4698 (@jjh4698) on CodePen.
---
Context
AngularJS에서는 Javascript eval()을 사용하지 않습니다. 대신에 AngularJS 자체 $parse를 사용합니다.
AngularJS에서 자체적으로 window
, document
, location
에 접근할 수 없습니다. 이는 global 영역에 무분별하게 접근하여서 위험성이 큽니다.
대신 AngularJS 컨트롤러 내부에 있는 자체 $window
,$location
을 사용합니다.
context 자체에 접근하기 위해서 this
키워드도 사용 가능합니다.
See the Pen Context 예제 by jjh4698 (@jjh4698) on CodePen.
---
Forgiving
Javascript 코드 내에서 a.b.c
를 eval()
하게 되면, exception이 발생합니다.
하지만 AngularJS Expression 내부에서는, undefined가 반환됩니다.
{{a.b.c}}
No Control Flow Statements
3항 연산자(a ? b : c
)를 제외한 flow control 구문을 AngularJS에서 사용할 수 없습니다. 이유는 AngularJS 핵심 철학에 따라 Controller에서는
어플리케이션 로직을 가질 수 없도록 하기 위함입니다.
No Function Declarations or RegExp creation with literal notation
Angular JS Expressions 내부에서 정규식을 사용할 수 없습니다. 이는 AngularJS가 템플릿 내부 model 변수를 변환하는 로직에 영향을 끼치는것을 막기 위해서 입니다. 대신 Expression Filter 사용을 고려 할 수 있습니다.
$event
ngClick
, ngFocust
Directive는 scope
안의 $event 객체를 사용합니다. 이 객체는 jQuery Event Object 입니다.
One-time Binding
::
키워드는 One-time Expressions 입니다. 한 번 바인딩 되고 나면 그 후의 digest 과정에서 제외됩니다.
Angular에서 수행하는 Digest Loop 속도를 최적화하고 리소스 관리 차원에서 이점이 있습니다.
See the Pen Untitled by jjh4698 (@jjh4698) on CodePen.
Value stabilization algorithm
One-time binding에서 expression 값은 digest cycle에서 값을 유지하고 있습니다.
::
로 시작하는 expression을 만났을떄 digest loop는 undefined가 아닌 한, 값을 V로 저장합니다.- expression의 결과를 마킹하고, digest loop를 빠져나가면서 expression을 dirty-checking watching하는 스케줄에서 제외시킵니다.
- 평상시처럼 digest looprk 가 실행됩니다.
- undefined일 경우, dirty-checking watch 스케줄을 그대로 놔두고, step 1으로 돌아갑니다.
One-time binding이 구체적으로 어느 이점이 있는가 ?
1번 정해지면 변경되지 않는 부분들
<div name="attr: {{::color}}">text: {{::name | uppercase}}</div>
Bidirectional Binding을 사용하더라도, 파라미터가 변경되지 않습니다.
someModule.directive('someDirective', function() {
return {
scope: {
name: '=',
color: '@'
},
template: '{{name}}: {{color}}'
};
});
<div some-directive name="::myName" color="My color is {{::myColor}}"></div>