Angularjs 雙向綁定時(shí)字符串的轉(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
因?yàn)檫@個(gè)是字符串類型需要轉(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}}顯示的時(shí)候,轉(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>
也能輸出正確結(jié)果
以上所述是小編給大家介紹的Angular js 雙向綁定時(shí)字符串的轉(zhuǎn)換成數(shù)字類型的問題,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
使用Angular緩存父頁(yè)面數(shù)據(jù)的方法
這篇文章主要介紹了使用Angular緩存父頁(yè)面數(shù)據(jù)的方法,需要的朋友可以參考下2017-01-01AngularJS 使用ng-repeat報(bào)錯(cuò) [ngRepeat:dupes]
這篇文章主要介紹了AngularJS 使用ng-repeat報(bào)錯(cuò) [ngRepeat:dupes] 的相關(guān)資料,需要的朋友可以參考下2017-01-01淺談AngularJS中$http服務(wù)的簡(jiǎn)單用法
這篇文章主要介紹了淺談AngularJS中$http服務(wù)的簡(jiǎn)單用法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05AngularJS 實(shí)現(xiàn)點(diǎn)擊按鈕獲取驗(yàn)證碼功能實(shí)例代碼
本文通過實(shí)例代碼給大家介紹了AngularJS 實(shí)現(xiàn)點(diǎn)擊按鈕獲取驗(yàn)證碼功能,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-07-07AngularJS實(shí)現(xiàn)Model緩存的方式
這篇文章主要介紹了AngularJS實(shí)現(xiàn)Model緩存的方式,分享了多種AngularJS實(shí)現(xiàn)Model緩存的方法,感興趣的小伙伴們可以參考一下2016-02-02angularjs實(shí)現(xiàn)的購(gòu)物金額計(jì)算工具示例
這篇文章主要介紹了angularjs實(shí)現(xiàn)的購(gòu)物金額計(jì)算工具,涉及AngularJS事件監(jiān)聽、數(shù)值計(jì)算相關(guān)操作技巧,需要的朋友可以參考下2018-05-05