简体   繁体   English

何时在Angular.js中使用$ parse

[英]When to use $parse in Angular.js

角j中的$parse提供程序如何工作,在哪种情况下它将是有用的,在哪种情况下赋值fn可用。

$parse is useful for evaluating a string and returning a function that can manipulate a model, or call a function. $ parse对于计算字符串并返回可以操作模型或调用函数的函数非常有用。 Any variables within the string is resolved from the context that is passed into the function. 字符串中的任何变量都是从传递给函数的上下文中解析的。

Getting and Setting a Property of a Model 获取和设置模型的属性

$parse is useful for compiling an angular expression into a function that can get/set a model. $ parse对于将角度表达式编译为可以获取/设置模型的函数非常有用。

For example, if you want to get/set user.name , you can use $parse('user.name') : 例如,如果要获取/设置user.name ,可以使用$parse('user.name')

Getter 消气

var context = { user: { name: 'john'}};
var getter = $parse('user.name');
var name = getter(context);
console.log(name); // outputs 'john'

Setter 二传手

var context = { user: { name: 'john'}};
var setter = $parse('user.name').assign;
setter(context, 'tom');
console.log(context.user.name); //outputs tom

$scope can also serve as the context: $ scope也可以作为上下文:

$scope.user = { name: 'john' };
var getter = $parse('user.name');
var name = getter($scope);
console.log(name); // outputs 'john'

Calling a Function 调用函数

$parse may also be used to compile an angular expression into a callable function. $ parse也可用于将角度表达式编译为可调用函数。

For example, if you want to call a function called helloWorld() : 例如,如果要调用名为helloWorld()的函数:

var context = { 
      helloWorld: function(name) { 
           alert(name); 
      }, 
      user: {
           name:'john'
      }
};
var fn = $parse('helloWorld(user.name)');
fn(context); // alerts 'john'

You want to use $parse when you want to convert angular expression into javascript function. 如果要将角度表达式转换为javascript函数,则需要使用$ parse。 Angular expression is a string such as {{ expression }}. 角度表达式是一个字符串,例如{{expression}}。

Take a look at this article. 看看这篇文章。 $parse $解析

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

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