It might be tempting to think of Angular view expressions as Javascript expressions, but that is not entirely correct, since angular does not use a Javascript eval() to evaluate expressions. You can think of Angular expressions as Javascript expressions with following diffences:
1.Attirbute Evaluation:
Evaluation of all properties are against the scope, doing the evaluation, unlike in Javascript where the expressions are evaluate against the global window.
2.Forgiving:
Expression evaluation is forgiving to undefined and null, unlike in Javascript, where such evaluations generate NullPointerExceptions.
3.No Control Flow Statements :
You can pass result of expression evaluations through filter chains. For example to convert date object into a local specific human-readable format.
If, on the other hand, you do want to run arbitrary Javascript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
index.html
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.0.4angular.min.js"></script>
</head>
<body>
1+2={{1+2}}
</body>
</html>
Result:
1+2 = 3
You can try evaluating different expressions here:
index.html
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.0.4angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="expcnt" class="expressions">
Expression:
<input type="text" ng-model="expr" size="80" />
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs">
[<a href="" ng-click="removeExp($index)">X</a>]
<tt>{{expr}}</tt> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
</body>
</html>
script.js
function expcnt($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);
};
}
No comments:
Post a Comment