方向1:模型數據(model) 綁定 到視圖(view)html
實現方法1:{{model變量名}} app
$scope.num=10
<p>{{num}}</p>
實現方法2: 經常使用指令(ngRepeat、ngIf、ngShow/Hide/Src....) ide
$scope.list=[{name:'sam',age:22},{name:'tom',age:37},{name:'kim',age:28}]
<tr ng-repeat='std in list'> <td>{{std.name}}</td> <td>{{std.age}}</td> </tr>
方向2:將視圖(view)中用戶輸入的數據 綁定到 模型數據(model)spa
實現方法:ngModel指令 用在表單組件中(input select textarea。。。)code
PS:$watch監聽模型變量值的改變------>執行指定的方法
$scope.$watch('變量名',function(){...});htm
1 <!DOCTYPE html> 2 <html ng-app="myApp"> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="js/angular.js"></script> 7 </head> 8 <body ng-controller="myCtro"> 9 10 <!--將多選框的勾選數據給model --> 11 複選框:<input type="checkbox" ng-model="isAgree"/> 12 <br> 13 14 <!--將選擇框的model數據給ng-model--> 15 <!--ng-options 動態生成選項 --> 16 <select ng-model="sel2" ng-options="sel2.name for sel2 in selection"></select> 17 <p>{{sel2.name}}</p> 18 <script> 19 var app=angular.module('myApp',['ng']); 20 21 app.controller('myCtro',function($scope){ 22 //$watch能夠監聽view數據是否改變,便於觀察現象 23 $scope.$watch('isAgree',function(){ 24 console.log($scope.isAgree); 25 }); 26 $scope.$watch('sel',function(){ 27 console.log($scope.sel); 28 }); 29 30 $scope.selection=[ 31 {name:'model',value:5}, 32 {name:'modren',value:4}, 33 {name:'moon',value:1}, 34 {name:'morning',value:3} 35 ]; 36 //爲select標籤設置一個selected 選項 37 $scope.sel2=$scope.selection[1]; 38 39 $scope.$watch('sel2',function() { 40 console.log($scope.sel2.value); 41 }) 42 }) 43 </script> 44 </body> 45 </html>
三、利用ng-model ng-checked 雙向數據傳輸 實現全選/部分選擇的判斷blog
<!DOCTYPE html> <html ng-app="myApp"> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="js/angular.js"></script> </head> <body ng-controller="myCtro"> <table> <thead> <tr> <th>請選擇</th> <th>姓名</th> <th>生日</th> </tr> </thead> <tbody> <tr ng-repeat="tem in list"> <td> <input type="checkbox" ng-model="tem.ischecked" ng-checked="selectAll"/> </td> <td>{{tem.name}}</td> <td>{{tem.birthday}}</td> </tr> </tbody> </table> <input type="checkbox" ng-model="selectAll"/>全選/取消全選 <br/> <button ng-click="getMsg()">查看</button> <script> var app=angular.module('myApp',['ng']); app.controller('myCtro',function($scope){ $scope.list=[ {name:'Michael',birthday:'2016-05-01',ischecked:false}, {name:'Golden',birthday:'2016-05-04',ischecked:false} ]; //監聽的目的:經過全選或者取消全選時,ng-checked方向1的綁定確實會生效 //當時不會直接修改 //$watch=onchange $scope.$watch('selectAll',function(){ angular.forEach($scope.list,function(value,key){ $scope.list[key].ischecked=$scope.selectAll; }) }); $scope.getMsg=function(){ var str=""; //遍歷的一種方法 angular.forEach($scope.list,function(value,key){ console.log(value); if(value.ischecked){ str+=value.name+"被選中了"; } }); if(str===""){ str='什麼都沒選中'; } alert(str); } }); </script> </body> </html>