加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何在Angular.js中解析

发布时间:2020-12-17 07:42:41 所属栏目:安全 来源:网络整理
导读:可能这是最简单的事情,但我无法解析一个字符串到Int在角度.. 我想做什么: input type="text" ng-model="num1"input type="text" ng-model="num2"Total: {{num1 + num2}} 如何求和这些num1和num2值? 日Thnx! 您不能(至少在此刻)在角度表达式中使用parseInt
可能这是最简单的事情,但我无法解析一个字符串到Int在角度..

我想做什么:

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

Total: {{num1 + num2}}

如何求和这些num1和num2值?

日Thnx!

您不能(至少在此刻)在角度表达式中使用parseInt,因为它们不直接评估.报价 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.

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

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

…但是这显然不会解析它们的值,只能将它们转换为Numbers(如果此转换导致NaN,则数字过滤器会阻止显示null).所以选择适合你特定情况的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读