How to parseInt in Angular.js

前端 未结 7 1667
生来不讨喜
生来不讨喜 2020-11-28 13:07

Probably, it is the simplest thing but I couldn\'t parse a string to Int in angular..

What I am trying to do:



        
相关标签:
7条回答
  • 2020-11-28 13:49

    Inside template this working finely.

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
    
    <div ng-app="">
    <input ng-model="name" value="0">
    <p>My first expression: {{ (name-0) + 5 }}</p>
    </div>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 14:01

    This are to way to bind add too numbers

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script>
    
    var app = angular.module("myApp", []);
    
    app.controller("myCtrl", function($scope) {
    $scope.total = function() { 
      return parseInt($scope.num1) + parseInt($scope.num2) 
    }
    })
    </script>
    <body ng-app='myApp' ng-controller='myCtrl'>
    
    <input type="number" ng-model="num1">
    <input type="number" ng-model="num2">
    Total:{{num1+num2}}
    
    Total: {{total() }}
    
    
    </body>
    </html>

    0 讨论(0)
  • 2020-11-28 14:02

    Perform the operation inside the scope itself.

    <script>
    angular.controller('MyCtrl', function($scope, $window) {
    $scope.num1= 0;
    $scope.num2= 1;
    
    
      $scope.total = $scope.num1 + $scope.num2;
    
     });
    </script>
    <input type="text" ng-model="num1">
    <input type="text" ng-model="num2">
    
    Total: {{total}}
    
    0 讨论(0)
  • 2020-11-28 14:04
    <input type="number" string-to-number ng-model="num1">
    <input type="number" string-to-number ng-model="num2">
    
    Total: {{num1 + num2}}
    

    and in js :

    parseInt($scope.num1) + parseInt($scope.num2)
    
    0 讨论(0)
  • 2020-11-28 14:06
    var app = angular.module('myApp', [])
    
    app.controller('MainCtrl', ['$scope', function($scope){
       $scope.num1 = 1;
       $scope.num2 = 1;
       $scope.total = parseInt($scope.num1 + $scope.num2);
    
    }]);
    

    Demo: parseInt with AngularJS

    0 讨论(0)
  • 2020-11-28 14:08

    Option 1 (via controller):

    angular.controller('numCtrl', function($scope, $window) {
       $scope.num = parseInt(num , 10);
    }
    

    Option 2 (via custom filter):

    app.filter('num', function() {
        return function(input) {
           return parseInt(input, 10);
        }
    });
    
    {{(num1 | num) + (num2 | num)}}
    

    Option 3 (via expression):

    Declare this first in your controller:

    $scope.parseInt = parseInt;
    

    Then:

    {{parseInt(num1)+parseInt(num2)}}
    

    Option 4 (from raina77ow)

    {{(num1-0) + (num2-0)}}
    
    0 讨论(0)
提交回复
热议问题