已經了解了angular的基礎知識以后,我們繼續開始了解angular的基礎模塊,首先在寫angular應用時需要引入angularjs
在使用angular時必須為它定義邊界(angular的作用范圍)
1、如果想構建angular應用只需要
<html ng-app="應用名">
2、如果需要angular操作部分區域的數據,則將相應的ng-app寫到對應的標簽上
<html> ....... <body> ....... <!--angular處理區域--> <div ng-app> </div> <!--結束--> ....... .... </body> </html>
模塊:
1、數據顯示
可以使用{{}}或ng-bind
<p>{{txt}}</p>
或
<p ng-bind="txt"></p>
兩者的卻別在於html沒有加載完畢{{txt}}回直接顯示到頁面,直到angular渲染該綁定數據(這種行為有可能將{{binding}}讓用戶看到);而ng-bind則是在angular渲染完畢后將數據顯示
2、ng-controller
該命令用戶管理視圖和模型之間的關系的控制器(單頁面中可以根據復雜程度引入多個控制器)
3、ng-model
將值綁定到表單元素上
<form > <input type='checkbox' ng-model='value'/> </form>
4、ng-watch
用戶監聽一個表達式的變化,調用相應的回調
<div ng-controller='testController'> <input ng-model='start_value'/> <label>{{end_value}}</label> </div> <script> var app = angular.module('myapp', []); app.controller('testController', function($scope) { $scope.start_value =1; function change_value() { $scope.end_value = $scope.start_value; } $scope.$watch('start_value', change_value); }); </script>
5、angular提供了一系列命令與原生的瀏覽器事件相對應,包括ng-change、ng-click、ng-submit、ng-dbclick等
6、ng-repeat
用於數據迭代
<html ng-app='myapp'> <script src='angular.js'></script> <body> <table ng-controller='tableController'> <tr ng-repeat='repeat in repeat_list'> <td >{{repeat.name}}</td> </tr> </table> <script> var app = angular.module('myapp', []); app.controller('tableController', function($scope) { $scope.repeat_list = [ {name:'test01'}, {name:'test02'} ]; }); </script> </body> </html>
6、ng-show、ng-hide
用於顯示或隱藏綁定元素,行為相反,ng-show為true時顯示,false隱藏
<div ng-controller='testController'> <label ng-show='label_show'>哈哈</label> <button ng-click="toggle_label()">切換</button> </div> <script type="text/javascript"> function testController($scope) { $scope.label_show = false; $scope.toggle_label = function () { $scope.label_show = !$scope.label_show; } } </script>
7、ng-css、ng-style
用於在應用中動態設置樣式,接受一個表達式,表達式的取值方式
(1)一個表示css類名的字符串
(2)css類名數組
(3)類名到布爾值的映射
<div ng-controller='testController'> <label ng-class='test'>哈哈</label>
<label ng-class='{selected: true, on:false}'>哈哈</label>
</div> <script type="text/javascript"> function testController($scope) { $scope.test = 'selected on';//方式1 $scope.test = ['selected', 'on'];//方式2 } </script>
8、ng-src、ng-link
用於img、a加載內容,有的時候img或a進行簡單的<img src={{binding}}/>數據綁定,angular沒有機會攔截請求。因此使用ng-src屬性
基本上就這些了