Angularjs expression Detailed and simple example _angularjs

Source: Internet
Author: User
Tags readable javascript eval


An expression (Expressions) is a code fragment of class JavaScript, usually placed in a bound region (such as {{expression}}). An expression resolves execution through the $parse service (http://code.angularjs.org/1.0.2/docs/api/ng. $parse).



For example, the following are valid expressions in angular:


    1. 1+2
    2. 3*10 | Currency
    3. User.Name


Angular expression vs. Js expression



It's easy to associate a angular view expression with a JavaScript expression, but that's not exactly true because angular is not evaluated by the JavaScript eval (). You can imagine a angular expression as a JavaScript expression with the following differences:


    1. Property Evaluation: All properties are evaluated for scope, and JavaScript is for window objects.
    2. Tolerance (forgiving): expression evaluation, for undefined and null,angular is tolerant, but JavaScript produces nullpointerexceptions (-_-!!!! How I haven't seen it.
    3. No Process Control statements: in angular expressions, we can't do any of the following: conditional branching, looping, throwing exceptions.
    4. Filter (filters): We can pass the result of an expression to the filter chain (filter chains). For example, convert a Date object to a locally specified human-readable format.


On the other hand, if we want to execute arbitrary JavaScript code (in the angular expression), we can write that code into a method of controller and call it. If we want to eval () a angular expression in JavaScript, we can use the $eval () method.


<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="ExpressionTest">
<head>
  <meta charset="UTF-8">
  <title>expression-e1</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body ng-controller="MyCtrl">
1 + 2 = {{1+2}}
<br/>
Expression:
<input type="text" ng-model="expr"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
  <li ng-repeat="expr in exprs">
    [<a ng-click="removeExp($index)" href="">X</a>]
    <tt>{{expr}}</tt>=><span ng-bind="$parent.$eval(expr)"></span>
  </li>
</ul>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("ExpressionTest", []);
  app.controller("MyCtrl", function ($scope) {
    var exprs = $scope.exprs = [];
    $scope.expr = "3*10|currency";
    $scope.addExp = function(expr) {
      exprs.push(expr);
    };
    $scope.removeExp = function (index) {
      exprs.splice(index, 1);
    };
  });
</script>
</body>
</html>


Second, the attribute evaluation (property evaluation)



The context of the angular expression parsing environment is scope, while JavaScript is window (should refer to strict mode Evel), angular needs to access the Global Window object through $window. For example, if we need to call alert () defined on a Window object in an expression, we need to use $window.alert (). The idea is to avoid accidental access to the public property (global State) (a small homologous bug?). A common source of subtle bugs).


<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="PropertyEvaluation">
<head>
  <meta charset="UTF-8">
  <title>PropertyEvaluation</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body>
<div ng-controller="MyCtrl">
  Name: <input ng-model="name" type="text"/>
  <button ng-click="greet()">Greet</button>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("PropertyEvaluation", []);
  app.controller("MyCtrl", function ($scope,$window) {
    $scope.name = "Kitty";
    $scope.greet = function() {
      $window.alert("Hello " + $scope.name);
    };
  });
</script>
</body>
</html>


Third, forgiving (tolerance, fault tolerance?) )



An expression evaluation is tolerant of undefined and null. In JavaScript, when a is not object, the A.B.C is evaluated, and an exception is thrown. Sometimes this is reasonable for a common language, and expression evaluation is mainly used for data binding, in general form as follows:



{{A.B.C}}}



If a does not exist, nothing appears to be more reasonable than to throw an exception (unless we wait for the server response to be defined soon). If expression evaluation is not tolerant enough, then we write the binding code in such a confusing way:



{{(a| | {}). b| | {}). C}}//This ...



Similarly, when referencing a function a.b.c (), if it is undefined or null, then simply return to undefined.



Four, no Control process statement (no controls flow statements)



We cannot write a Process Control statement in an expression. The reason behind this is that the core system of angular is that the logic of application should be in the controller (scope), not in view. If we need to add conditional branches, loops, or throw exceptions to a view expression, you can delegate the JavaScript method instead (you can invoke the method in scope).



V. Filter (Filters)



When we present our data to the user, we may need to convert the data from the original format to a friendly (readable) format. For example, we have a data object that needs to be formatted according to geography before it is displayed to the user. We can pass an expression to a series of filters, such as:



name | Uppercase



This expression evaluation can simply pass the value of name to the uppercase filter.



Chained filters Use this syntax:



Value | Filter1 | Filter2



We can also send a colon-delimited parameter to filter, for example, to display 123 in two-bit decimal format:



123 | Number:2



Six, prefix "$"



We might wonder, what is the meaning of the prefix "$"? It is a simple prefix used by angular to make its API name distinguishable from other APIs (conflict prevention). If angular does not use $, then the a.length () evaluation returns undefined. Because neither a nor angular itself defines this property.



This will change the behavior of this expression, considering that the future version of angular may choose to increase the length of the method. What's worse, we developers may create a length attribute that will conflict with angular. This problem exists because angular expands the currently existing object by adding a method. By adding the prefix "$", angular retains a specific namespace, so angular developers and developers using angular can coexist harmoniously.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.