標籤:
範圍
範圍($scope)和應用的資料模型相關聯的,同時範圍也是運算式執行的上下文。$scope對象是定義應用商務邏輯、控制器方法和視圖屬性的地方。 範圍是視圖和控制器之間的膠水。在應用將視圖渲染並呈獻給使用者之前,視圖中的模板會和範圍進行串連,然後應用會對DOM進行設定以便將屬性變化通知給AngularJS。
基於動態綁定,我們在修改視圖資料時立刻更新$scope,而$scope發生變化時也會立刻渲染視圖。
| 12345678910111213141516171819202122232425 |
<script type="text/javascript"> function loadController($scope) { $scope.name = "部落格園"; $scope.loadAgain = function () { $scope.name = "我的部落格"; }; };</script> <div ng-app> <div ng-controller="loadController"> <input ng-model=‘name‘/> <button ng-click="loadAgain()"> 切換</button> <hr /> <span ng:bind="name"> <span ng:bind="name"></span> <br /> <span ng_bind="name"> <span ng_bind="name"></span> <br /> <span data-ng-bind="name"> <span data-ng-bind="name"></span> <br /> <span x-ng-bind="name"> <span x-ng-bind="name"></span> </div></div> |
上面的代碼中,我們給一個 div 元素指定了一個loadController(控制器),那麼div 元素之內,就是 loadController 這個函數運行時, $scope 這個注入資源的控制範圍。
在這個控制範圍內的html中,可以訪問到$scope的變數:$scope.name,函數$scope.loadAgain。
資料繫結和模板
前面已經講過了,在頁面範圍範圍內可以通過ng-model、ng-bind等之類的指令來綁定變數。
其實還可以使用{{name}}來完成資料繫結。
說說模板吧,模板的綁定有三種:
1.頁面內直接寫html代碼(前面的資料繫結就是了)
2.使用script標籤自訂模板,如下
| 12345678910111213141516171819202122232425262728 |
<script type="text/javascript"> function tablelist($scope) { $scope.userlist = [{ name: "張三", age: "23" }, { name: "李四", age: "25"}] }; </script> <script type="text/ng-template" id="tpl"> <table ng-controller="tablelist"> <tr> <th> 姓名 </th> <th> 年齡 </th> </tr> <tr ng-repeat="app in userlist"> <td> {{app.name}} </td> <td> {{app.age}} </td> </tr> </table></script> <div ng-include src="‘tpl‘"></div> |
3.引用外部檔案
建立test.html模板頁並清除所有代碼,粘貼如下代碼儲存
| 123456789101112131415161718 |
<table ng-controller="tablelist"> <tr> <th> 姓名 </th> <th> 年齡 </th> </tr> <tr ng-repeat="app in userlist"> <td> {{app.name}} </td> <td> {{app.age}} </td> </tr></table> |
當前頁直接引用test.html,<div ng-include src="‘test.html‘"></div>
效果都是一樣的:
模板引用中用到了 ng-include,還有渲染指令 ng-repeat把對象數組迴圈渲染到了頁面,ng-repeat還提供了幾個可使用的變數:
$index 當前索引
$first 是否為頭元素
$middle 是否為非頭非尾元素
$last 是否為尾元素
Angular JS 範圍和資料繫結