在AngularJS表达式中使用变量? [英] Using a variable within AngularJS expression?

查看:47
本文介绍了在AngularJS表达式中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,但我想知道我是否可以在AngularJS表达式中使用JS变量(不确定它是否称为表达式).我可以演示的最简单方法是:

I'm new to Angular, but I was wondering am I able to use a JS variable within an AngularJS expression (not sure if it's called an expression). The simplest way I can demonstrate is this:

<code>
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>
        var number = 10;
    </script>
    <div ng-app="">
        <p>My expression: {{ 5 + number}}</p>
    </div>
</code>

有办法吗?

推荐答案

否,您不能在Angular表达式中使用全局变量(或函数).角表达式只是属性,字符串而不是Javascript代码也是如此.角度解析器( $ parse 服务,源代码)获取这些属性,对其进行解析并求值针对Angular应用的作用域对象.因此,为了在Angular表达式中使用任何内容,必须在相应的作用域对象上进行定义.

No, you cannot use global variables (or functions) in Angular expressions. Angular expressions are just attributes, so are strings and not Javascript code. Angular parser ($parse service, sourse code) takes those attributes, parses them and evaluates against scope object of the Angular app. So in order to use anything in Angular expression it must be defined on the corresponding scope object.

这篇关于在AngularJS表达式中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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