爱编程
AngularJS HTML页面模板转换成动态显示
2015-3-4 Jessie
HTML代码:

<!DOCTYPE html>
<html ng-app>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RunJS</title>
<script id="others_angular_103" type="text/javascript" class="library" src="/js/sandbox/other/angular.min.js"></script>

</head>
<body>
<!--练习一 计算-->
1+2={{1+2}}
<!--HTML页面模板转换成动态显示-->
<ul>
<li>
<span>Nexus S</span>
<p>
Fast just got faster with Nexus S.
</p>
</li>
<li>
<span>Motorola XOOM™ with Wi-Fi</span>
<p>
The Next, Next Generation tablet.
</p>
</li>
</ul>
<br>
<br>
<div ng-controller="PhoneListCtrl">
<ul>
<li ng-repeat="phone in phones">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>

<!--搜索迭代 全文搜索功能-->
<div class="container-fluid" ng-controller="PhoneListCtrl">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->

Search: <input ng-model="query">

</div>
<div class="span10">
<!--Body content-->
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
<!--搜索结合默认排序,搜索结合选择排序-->
<div ng-controller="PhoneListCtrl2">
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>

<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>

<!--图片模板,需要用ng-src属性,如果我们仅仅用一个正常src属性来进行绑定(<img src="{{phone.imageUrl}}">),浏览器会把AngularJS的{{ 表达式 }}标记直接进行字面解释,并且发起一个向非法url,因为浏览器载入页面时,同时也会请求载入图片,AngularJS在页面载入完毕时才开始编译,浏览器请求载入图片时{{phone.imageUrl}}还没得到编译!-->
<img ng-src="{{phone.imageUrl}}">

</body>
</html>

下面是javascript代码,加入到html中:


 var model = angular.module('myApp', []); 
model.controller('MyCtrl',PhoneListCtrl);

function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with abc."},
{"name": "aotorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet."},
{"name": "MOTOROLA XOOM™",
"snippet": "ahe Next, Next Generation tablet."}
];
}

function PhoneListCtrl2($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S.",
"age": 1},
{"name": "Motorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet.",
"age": 0},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next Generation tablet.",
"age": 2}
];

$scope.orderProp = 'age';
}
//http从后台得到数据
function PhoneListCtr3($scope, $http) {
$http.get('test/test!testAngularJs.action').success(function(data) {
$scope.phones = data;
});

$scope.orderProp = 'age';

}