[英]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. 字符串中的任何变量都是从传递给函数的上下文中解析的。
$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'
$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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.