How to parseInt in Angular.js

前端 未结 7 1668
生来不讨喜
生来不讨喜 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 14:09

    You cannot (at least at the moment) use parseInt inside angular expressions, as they're not evaluated directly. Quoting the doc:

    Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

    Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

    So you can define a total() method in your controller, then use it in the expression:

    // ... somewhere in controller
    $scope.total = function() { 
      return parseInt($scope.num1) + parseInt($scope.num2) 
    }
    
    // ... in HTML
    Total: {{ total() }}
    

    Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0 op:

    Total: {{num1-0 + (num2-0)|number}}
    

    ... but that'll obviously won't parseInt values, only cast them to Numbers (|number filter prevents showing null if this cast results in NaN). So choose the approach that suits your particular case.

    0 讨论(0)
提交回复
热议问题