表达式是AngularJS视图中表现Scope数据最简单的方式。把表达式封装在花括号内{{expression}},AngularJS的编译器会把它编译成HTML元素,从而显示表达式的结果。比如说:{{1+5}}显示出来为6,{{"string"+"int"}}为stringint。同样表达式还可以使用JavaScript来进行一些操作等等,好我们来看代码。
<!doctype html>
<html ng-app="myApp">
<head>
<title>Angular</title>
<style type="text/css">
a{color: blue;text-decoration: underline;cursor: pointer;}
</style>
<body>
<div ng-controller="myController">
<h1>Expressions</h1>
Array:<br>
{{myArr}}<hr><!--表达式 显示scope中的myArr-->
Elements removed from array:<br>
{{removedArr}}<hr><!--表达式 显示scope中的removedArr-->
<a ng-click = "myArr.push(Math.floor(Math.random()*100+1))"><!--点击时生成大于0小于100随机数并且添加到myArr数组中-->
click to append a value to the array
</a><hr>
<a ng-click = "removedArr.push(myArr.shift())"><!--删除并获取到myArr中第一个元素添加到removedArr中-->
click to remove the first value from the array
</a><hr>
Size of Array:<br>
{{myArr.length}}<hr><!--显示myArr的长度-->
Max number removed frome the array:<br>
{{Math.max.apply(Math,removedArr)}}<hr><!--获取removedArr中的最大值-->
</div>
<script type="text/javascript" src="../angular.js"></script>
<script type="text/javascript" src="expressions_javascript.js"></script>
</body>
</head>
</html>
angular.module('myApp',[]).controller('myController',function($scope){
$scope.Math = window.Math;
$scope.myArr = [];
$scope.removedArr = [];
});
其实做到这里,使用Angluar的优势就出来了。这个demo虽然不难,但是对于一个大型网站来说是不是angular构建的就有很大的区别。它可以改善一个网站的可扩展性以及可维护性。真的用起来还是很爽的。