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

来源:互联网 发布:淘宝男装模特红人 编辑:程序博客网 时间:2024/05/20 21:47
这篇文章主要介绍了AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值的相关资料,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下

在"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);//运行时赋值columnmapcolumnmap = 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。

阅读全文
0 0