AngularJS雙向繫結,手動實施觀察

來源:互聯網
上載者:User

標籤:

 

實現這樣的一個需求:頁面中某個地方顯示某個文字框的值經過計算得到的結果,而且是文字框值每次變化顯示的計算結果也跟著動態變化。

 

在controller中可以聲明一個對象,它的一個欄位用來儲存初始值:

 

$scope.funding = {startingEstimate:0};

 

以上,聲明了一個funding對象,它的startingEstimate欄位用來儲存初始值,初始值這裡是0.

 

在controller中還應該聲明一個函數,用來把根據初始值計算得到的結果賦值給funding對象的另外一個欄位。

 

$scope.computeNeeded = function(){
    $scope.funding.needed = $scope.funding.startingEstimate * 10;
};

 

以上,聲明了computeNeeded函數,它把funding對象startingEstimate值進過計算後的結果賦值給了funding對象的另外一個欄位needed。

 

好了,頁面中的input需要和funding對象的startingEstimate雙向繫結起來,用ng-model;input中每次值變化需要調用computeNeeded,用ng-change:

 

初始值:<input type="text" ng-model="funding.startingEstimate" ng-change="computeNeeded()">

 

至於顯示結果,只管向funding對象的needed欄位要就好了:

 

計算值:{{funding.needed}}

 

可是,還有一點小問題:現在,只有當input中的值發生變化的時候才會觸發computeNeeded()方法,我們希望在頁面載入的時候就執行computedNeeded方法。

 

為此,AngularJS為我們準備了$scope.$watch(被觀察對象,執行的動作),可以把funding對象的startingEstimate欄位列為被觀察對象,startingEstimate欄位的每次變化,都執行computedNeeded()這個動作,包括給startingEstimate欄位初始賦值的時候。

 

$scope.$watch(‘funding.startingEstimate‘, $scope.computeNeeded);

 

完整代碼如下:

 

<!doctype html>
<html ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
    <script src="angular.min.js"></script>
    <script>
        var myApp = angular.module("myApp",[]);
        
        myApp.controller("MyController",[‘$scope‘,function($scope){
            $scope.funding = {startingEstimate:0};
            
            $scope.computeNeeded = function(){
                $scope.funding.needed = $scope.funding.startingEstimate * 10;
            };
            
            $scope.$watch(‘funding.startingEstimate‘, $scope.computeNeeded);
            
            $scope.finish = function(){
                alert("done");
            };
        }]);
    </script>
</head>
<body ng-controller="MyController">
    <form ng-controller="MyController" ng-submit="finish()">
        初始值:<input type="text" ng-model="funding.startingEstimate" ng-change="computeNeeded()">
        計算值:{{funding.needed}}
        
        <input type="submit" value="提交"> 
    </form>
</body>
</html>

 

總結:

 

● 雙向繫結:ng-model
● 文字框值變化事件:ng-change
● 對某個對象實施觀察:$scope.$watch(被觀察對象,執行的動作)
● 表單提交:ng-submit
● 其它事件:ng-click, ng-dblclick

 

 

參考資料:<<用AngularJS開發下一代Web應用>>

AngularJS雙向繫結,手動實施觀察

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.