AngularJS中使用$parse或$eval在运行时对Scope变量赋值
2016-01-25 09:58
531 查看
在"AngularJS中自定义有关一个表格的Directive"中自定义了一个有关表格的Direcitve,其表格的表现方式是这样的:
<table-helper datasource="customers" clumnmap="[{name: 'Name'}, {street: 'Street'}, {age: 'Age'}, {url: 'URL', hidden: true}]"></table-helper>
以上,变量colmnmap的值是事先定义在了Scope中的:
AngularJS中,还有一种运行时给Scope变量赋值的办法,那就是在link函数中使用$parse或$eval方法。
在Direcitve的呈现方面和以前一致:
<table-helper-with-parse datasource="customers" columnmap="[{name: 'Name'},...]"></table-helper-with-parse>
Directive大致是这样:
<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);
相关文章推荐
- Angular源码分析之$compile
- 在AngularJS中如何使用谷歌地图把当前位置显示出来
- AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值
- AngularJS中的Directive自定义一个表格
- AngularJS中的Directive实现延迟加载
- AngularJS入门心得之directive和controller通信过程
- AngularJS控制器controller正确的通信的方法
- AngularJS中自定义有关一个表格的Directive
- 关于ng-repeat的track by $index
- AngularJS in Action读书笔记1——扫平一揽子专业术语
- angularjs 复制
- angularjs 排序
- angular-xeditable
- AngularJs ng-route路由详解
- Angular复习笔记(一)
- AngularJs 禁止模板缓存
- AngularJS展示数据的ng-bind指令和{{}} 区别
- AngularJS中监视Scope变量以及外部调用Scope方法
- AngularJS使用ngOption实现下拉列表的实例代码
- 從Knockout到AngularJS