欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值

程序员文章站 2023-09-06 10:51:41
在"angularjs中自定义有关一个表格的directive"中自定义了一个有关表格的direcitve,其表格的表现方式是这样的:

在"angularjs中自定义有关一个表格的directive"中自定义了一个有关表格的direcitve,其表格的表现方式是这样的:

<table-helper datasource="customers" clumnmap="[{name: 'name'}, {street: 'street'}, {age: 'age'}, {url: 'url', hidden: true}]"></table-helper>

以上,变量colmnmap的值是事先定义在了scope中的:

return {
restrict: 'e',
scope: {
columnmap: '=',
datasource: '='
},
link:link,
template:template
}; 

angularjs中,还有一种运行时给scope变量赋值的办法,那就是在link函数中使用$parse或$eval方法

在direcitve的呈现方面和以前一致:

<table-helper-with-parse datasource="customers" columnmap="[{name: 'name'},...]"></table-helper-with-parse>

directive大致是这样:

var tablehelperwithparse = function($parse){
var template = "",
link = function(scope, element, attrs){
var headercols = [],
tablestart = '<table>',
tableend = '</table>',
table = '',
visibleprops = [],
sortcol = null,
sortdir = 1,
columnmap = null;
$scope.$watchcollection('datasource', render);
//运行时赋值columnmap
columnmap = scope.$eval(attrs.columnmap);
//或者
columnmap = $parse(attrs.columnmap)();
wireevents();
function rener(){
if(scope.datasource && scope.datasourse.length){
table += tablestart;
table += renderheader();
table += renderrows() + tableend;
rendertable();
}
}
};
return {
restrict: 'e',
scope: {
datasource: '='
},
link: link,
template: template
}
}
angular.module('direcitvesmodule')
.directive('tablehelperwithparse', tablehelperwithparse);

下面给大家介绍下$parse和$eval的不同

首先,$parse跟$eval都是用来解析表达式的, 但是$parse是作为一个单独的服务存在的。$eval是作为scope的方法来使用的。

$parse典型的使用是放在设置字符串表达式映射在真实对象上的值。也可以从$parse上直接获取到表达式对应的值。

var getter = $parse('user.name'); 
var setter = getter.assign; 
setter(scope, 'new name');
getter(context, locals) // 传入作用域,返回值
setter(scope,'new name') // 修改映射在scope上的属性的值为‘new value'

$eval 即scope.$eval,是执行当前作用域下的表达式,如:scope.$eval('a+b'); 而这个里的a,b是来自 scope = {a: 2, b:3};

看看源码它的实现是

$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},

可以找到它也是基于$parse,不过它的参数已经被固定为this,就是当前的scope,所以$eval只是在$parse基础上的封装而已,是一种$parse快捷的api。