如何在parseInt函数Angular.js [英] How to parseInt in Angular.js

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

问题描述

也许,这是最简单的事情,但我无法解析字符串的角度来诠释。

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?

日Thnx!

推荐答案

您不能(目前至少)使用 parseInt函数角前pressions,因为里面他们不直接评估。引用 商务部

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

角不使用JavaScript的的eval()评估前pressions。
  相反角的 $解析服务处理这些前pressions。

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

角前pressions不必访问像全局变量
  窗口文件位置。此限制是故意的。它
  prevents偶然进入全球国家 - 的常见原因
  微妙的错误。

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.

所以,你可以在你的控制器定义共有()方法,然后使用它在EX pression:

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:

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

...但是,这会显然不会的 parseInt函数的值,只有的的他们的数字( |号过滤器prevents显示如果投结果 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.

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

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