&"/> &">

首頁  >  文章  >  web前端  >  分享Angular js 雙向綁定的實例教程

分享Angular js 雙向綁定的實例教程

零下一度
零下一度原創
2017-06-26 09:58:141143瀏覽

問題:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js?1.1.11"></script> 
</head>
<body>

<div ng-app="myApp">

<p ng-controller = "myContrl">结果为 <span ng-bind=""   ></span>
<input type="text" ng-model="first">{{first+second}}</p>
</div>
<script>var app = angular.module("myApp",[]);
    app.controller("myContrl",function($scope){
        $scope.first = 5;
        $scope.second =10;
    });</script>
</body>
</html>

顯示結果為

#但是,我要是輸入50,想要結果為60

因為這個是字串型別需要轉換成數字型別

解決方法:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js?1.1.11"></script> 
</head>
<body>

<div ng-app="myApp">

<p ng-controller = "myContrl">结果为 <span ng-bind=""   ></span>
<input type="text" ng-model="first">{{first *1+second*1}}</p>
</div>
<script>var app = angular.module("myApp",[]);
    app.controller("myContrl",function($scope){
        $scope.first = 5;
        $scope.second =10;
    });</script>
</body>
</html>

顯示即可正常也就是在 {{first *1+second*1}}顯示的時候,轉換了一下

#或者,啟用事件監聽

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js?1.1.11"></script> 
</head>
<body>

<div ng-app="myApp">

<p ng-controller = "myContrl">结果为 <span ng-bind=""   ></span>
<input type="text" ng-model="first">{{total}}</p>
</div>
<script>var app = angular.module("myApp",[]);
    app.controller("myContrl",function($scope){
        $scope.first = 5;
        $scope.second =10;
        $scope.total = parseInt($scope.first)+parseInt($scope.second);
        $scope.$watch(function(){return $scope.first;
        },function(newValue,oldValue){         if(newValue != oldValue){
            $scope.total = parseInt($scope.first)+parseInt($scope.second);
         }
        });
    });</script>
</body>
</html>

也能輸出正確結果

 <br>

以上是分享Angular js 雙向綁定的實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn