富贵资源网 Design By www.hznty.com

在"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。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。