简体   繁体   English

表达式中的表达式AngularJS

[英]Expression in an expression, AngularJS

Is it possible to evaluate an expression within an expression? 可以在表达式内求值吗?

For example: 例如:

<span ng-bind-template="{{test}}"></span>

Where test is as follows: 其中test如下:

$scope.test = '{{a}} is equal to {{b}}';

a and b can be anything, lets assume two integers. ab可以是任意值,假设两个整数。

So I want to essentially evaluate it twice. 因此,我想对其进行两次评估。

Maybe I should just create a filter and use $interpolate in there? 也许我应该只创建一个过滤器并在其中使用$ interpolate?

You can $compile it manually with: 您可以使用以下命令手动对其进行$编译

scope.a = "1";
scope.b = "1";
var element = $compile('{{a}} is equal to {{b}}')(scope);

You have several options. 您有几种选择。 A singular expression can be evaluated using the $parse service. 可以使用$parse服务评估单数表达式。 This is something without the mustaches, ie {{ }}. 这是没有胡须的东西,即{{}}。 Notice the first call creates a function for the expression, the second call passes an object to evaluate it against: 请注意,第一个调用为该表达式创建了一个函数,第二个调用传递了一个对象以针对该表达式进行求值:

parseA = $parse('a');
console.log(parseA({ a: 1 })); // 1 

A complex expression can be evaluated using $interpolate . 可以使用$interpolate评估复杂的表达式。 This will parse the code for the mustaches and evaluate the expressions inside them against an object you pass. 这将解析胡须的代码,并针对您传递的对象评估胡须中的表达式。 Again, first call creates the function for interpolation, the second call evaluates it against what you pass in. I believe this is what you are looking for: 再次,第一次调用将创建用于插值的函数,第二次调用将根据您传递的内容对其求值。我相信这就是您要寻找的内容:

interpolate = $interpolate('{{a}} is equal to {{b}}');
console.log(interpolate({ a: 1, b: 2})); // 1 is equal to 2 

Finally, if you want to have a full data-bound segment of code, you use $compile . 最后,如果要获得完整的数据绑定代码段,请使用$compile This will bind a $scope to the element, so it has listeners and participates in digest, etc. 这会将$scope绑定到元素,因此它具有侦听器并参与摘要等。

compile = $compile('<div>{{a}}</div>');
scope = $scope.$new();
scope.a = 1; 
compile(scope); // <div>1</div> 

Here is a full working fiddle using all three techniques: http://jsfiddle.net/jeremylikness/CAHKE/ 这是使用所有三种技术的完整工作提琴: http : //jsfiddle.net/jeremylikness/CAHKE/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM