|
2 | 2 | @name Expressions
|
3 | 3 | @description
|
4 | 4 |
|
5 |
| -Expressions are JavaScript-like code snippets that are usually placed in bindings such as |
| 5 | +# Angular Expressions |
| 6 | + |
| 7 | +Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as |
6 | 8 | `{{ expression }}`.
|
7 | 9 |
|
8 | 10 | For example, these are valid expressions in Angular:
|
@@ -88,7 +90,7 @@ You can try evaluating different expressions here:
|
88 | 90 | </example>
|
89 | 91 |
|
90 | 92 |
|
91 |
| -# Context |
| 93 | +## Context |
92 | 94 |
|
93 | 95 | Angular does not use JavaScript's `eval()` to evaluate expressions. Instead Angular's
|
94 | 96 | {@link ng.$parse $parse} service processes these expressions.
|
@@ -154,3 +156,44 @@ You cannot write a control flow statement in an expression. The reason behind th
|
154 | 156 | Angular philosophy that application logic should be in controllers, not the views. If you need a
|
155 | 157 | conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.
|
156 | 158 |
|
| 159 | +## `$event` |
| 160 | + |
| 161 | +Directives like {@link ng.directive:ngClick `ngClick`} and {@link ng.directive:ngFocus `ngFocus`} |
| 162 | +expose a `$event` object within the scope of that expression. |
| 163 | + |
| 164 | +<example module="eventExampleApp"> |
| 165 | + <file name="index.html"> |
| 166 | + <div ng-controller="EventController"> |
| 167 | + <button ng-click="clickMe($event)">Event</button> |
| 168 | + <p><code>$event</code>: <pre> {{$event | json}}</pre></p> |
| 169 | + <p><code>clickEvent</code>: <pre>{{clickEvent | json}}</pre></p> |
| 170 | + </div> |
| 171 | + </file> |
| 172 | + |
| 173 | + <file name="script.js"> |
| 174 | + angular.module('eventExampleApp', []). |
| 175 | + controller('EventController', ['$scope', function($scope) { |
| 176 | + /* |
| 177 | + * expose the event object to the scope |
| 178 | + */ |
| 179 | + $scope.clickMe = function(clickEvent) { |
| 180 | + $scope.clickEvent = simpleKeys(clickEvent); |
| 181 | + console.log(clickEvent); |
| 182 | + }; |
| 183 | + |
| 184 | + /* |
| 185 | + * return a copy of an object with only non-object keys |
| 186 | + * we need this to avoid circular references |
| 187 | + */ |
| 188 | + function simpleKeys (original) { |
| 189 | + return Object.keys(original).reduce(function (obj, key) { |
| 190 | + obj[key] = typeof original[key] === 'object' ? '{ ... }' : original[key]; |
| 191 | + return obj; |
| 192 | + }, {}); |
| 193 | + } |
| 194 | + }]); |
| 195 | + </file> |
| 196 | +</example> |
| 197 | + |
| 198 | +Note in the example above how we can pass in `$event` to `clickMe`, but how it does not show up |
| 199 | +in `{{$event}}`. This is because `$event` is outside the scope of that binding. |
0 commit comments