AngularJS中如何使用$parse或$eval在运行时对Scope变量
网络编程 2021-07-04 21:04www.168986.cn编程入门
这篇文章主要介绍了AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值的相关资料,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下
在",其表格的表现方式是这样的:
<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);
狼蚁网站SEO优化给大家介绍下$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。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程