標籤:
前言:
我們在做前端工作最重要的是把資料能展示給使用者看,展示的時候就是把資料繫結給某個元素。
1,簡單的資料繫結
html:
<!DOCTYPE html><html ng-app="MyModule"><head> <meta charset="utf-8"> <title>資料繫結</title></head><body> <div ng-controller="myCtl"> <p>{{greeting.text}},Angular</p> </div></body><script src="js/angular-1.3.0.js"></script><script src="js/dataBid.js"></script></html>
在上面描述中,{{}} 就是我們實現資料繫結的一個方法,下面把資料給 $scope就可以顯示出來了
var myModule = angular.module(‘MyModule‘,[]);myModule.controller(‘myCtl‘,function($scope){ $scope.greeting={ text:"hello" }})
看
但是,這裡有一個問題,當你寫完代碼按住 F5 狂重新整理頁面的時候,會發現在資料沒有綁定到頁面元素的時候,顯示的是我們的代碼{{greeting.text}}
這不是我們想要的結果,我們可以使用angularjs提供的第二種方法來顯示資料繫結,使用 ng-bind屬性
<div ng-controller="myCtl"> <p><span ng-bind="greeting.text"></span>,Angular</p> </div>
這樣顯示的時候就不會有代碼顯示出來了,接著問題來了(要問挖掘機哪家強?),開個玩笑,呵呵,其實差不多,你是你有兩種方式綁定,那我們該用哪一種比較好呢?其實,這是要分情境的,使用 ng-bind 是在主html裡比較好,而用到 {{}}呢,是放在模板中比較好。
2,雙向資料繫結
什麼是雙向資料繫結?簡單的說就是,資料從後端(指js邏輯這塊)展現到前端,從前端也能修改後端的資料。最經典的例子就是form表單提交了。
<!DOCTYPE html><html ng-app="MyModule"><head> <meta charset="utf-8"> <link rel="stylesheet" href="css/bootstrap.min.css"> <title>雙向資料繫結</title></head><body> <div class="row"> <div class="col-md-5"> <form action="" role="form" class="form-horizontal" ng-controller="formCtl"> <div class="form-group"> <label for="" class="col-md-2 contorl-label">登入名稱:</label> <div class="col-md-10"> <input type="text" class="form-control" placeholder="請輸入登入名稱/郵箱/手機號" ng-model="userInfo.loginUser"> </div> </div> <div class="form-group"> <label for="" class="col-md-2 contorl-label">密碼:</label> <div class="col-md-10"><input type="text" class="form-control" placeholder="請輸入密碼" ng-model="userInfo.pwd"></div> </div> <div class="form-group"> <!-- <label for="" class="col-md-2 contorl-label"></label> --> <div class="col-md-10 col-md-offset-2"> <div class="checkbox"> <label > <input type="checkbox" ng-model="userInfo.checked"> 自動登入 </label> </div> </div> </div> <div class="form-group"> <!-- <label for="" class="col-md-2 contorl-label"></label> --> <div class="col-md-10 col-md-offset-2"> <button id="btnGetFormVal" ng-click="getFormVal()" class="btn btn-primary">擷取Form表單的值</button> <!-- <input type="text" class="form-control" placeholder="" ng-modle=""> --> <button class="btn btn-default" ng-click="setFormVal()">設定Form表單的值</button> </div> </div> </form> </div> </div> <script src="js/angular-1.3.0.js"></script> <script src="js/doubleDataBid.js"></script></body></html>
View Code
看這個代碼,我們可以用 ng-model來把後端的資料繫結到前面的 input框內。同時使用 ng-click來調用 $scope所定義的方法,來擷取和修改form表單的值
var myModule = angular.module(‘MyModule‘,[]);myModule.controller(‘formCtl‘,function($scope){ $scope.userInfo = { loginUser:"duxg", pwd:‘12345678‘, checked:true } $scope.getFormVal=function(){ console.log($scope.userInfo); } $scope.setFormVal=function(){ $scope.userInfo={ loginUser:"nijie", pwd:"1212", checked:false } }})
在此說明,ng-bind適用於標籤元素,而ng-model適用於文本、選擇等元素。
3,總結:
資料繫結這塊很簡單,我們自己就很常用,就舉一個簡單的例子吧,我們常用的多條件查詢資料,那我們可以把要查詢的條件放到一個集合中去,等使用者改變那個條件,我們就去修改集合中對應的索引值對就好了,然後去調用ajax。是不是一樣的道理?
AngularJs-資料繫結