您好,登錄后才能下訂單哦!
小編給大家分享一下如何解決Angularjs中雙向綁定時字符串的轉(zhuǎn)換成數(shù)字類型的問題,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
問題:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myApp"> <p ng-controller = "myContrl">結(jié)果為 <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>
顯示結(jié)果為
但是,我要是輸入50,想要結(jié)果為60
因為這個是字符串類型需要轉(zhuǎn)換成數(shù)字類型
解決方法:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myApp"> <p ng-controller = "myContrl">結(jié)果為 <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}}顯示的時候,轉(zhuǎn)換了一下
或者,啟用事件監(jiān)聽
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myApp"> <p ng-controller = "myContrl">結(jié)果為 <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>
以上是“如何解決Angularjs中雙向綁定時字符串的轉(zhuǎn)換成數(shù)字類型的問題”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。