如何在 Angular.js 中解析 Int [英] How to parseInt in Angular.js

查看:28
本文介绍了如何在 Angular.js 中解析 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能,这是最简单的事情,但我无法以角度将字符串解析为 Int ..

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

我想做什么:

<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{num1 + num2}}

如何对这些 num1 和 num2 值求和?

How can I sum these num1 and num2 values?

谢谢!

推荐答案

您不能(至少目前)在 Angular 表达式中使用 parseInt,因为它们不是直接计算的.引用文档:

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

Angular 不使用 JavaScript 的 eval() 来计算表达式.相反,Angular 的 $parse 服务处理这些表达式.

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

Angular 表达式无法访问全局变量,例如windowdocumentlocation.这个限制是有意的.它防止意外访问全局状态 - 一个常见的来源细微的错误.

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.

所以你可以在你的控制器中定义一个 total() 方法,然后在表达式中使用它:

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() }}

不过,对于像添加数字这样简单的操作来说,这似乎相当庞大.另一种方法是使用 -0 op:

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}}

...但这显然不会 parseInt 值,只会 cast 到 Numbers(|number 过滤器阻止显示 null 如果此转换结果为 NaN).因此,请选择适合您特定情况的方法.

... 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.

这篇关于如何在 Angular.js 中解析 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆