亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

AngularJS中如何使用$parse或$eval在運(yùn)行時(shí)對(duì)Scope變量賦值

 更新時(shí)間:2016年01月25日 11:41:50   投稿:mrr  
這篇文章主要介紹了AngularJS中如何使用$parse或$eval在運(yùn)行時(shí)對(duì)Scope變量賦值的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下

在"AngularJS中自定義有關(guān)一個(gè)表格的Directive"中自定義了一個(gè)有關(guān)表格的Direcitve,其表格的表現(xiàn)方式是這樣的:

<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中,還有一種運(yùn)行時(shí)給Scope變量賦值的辦法,那就是在link函數(shù)中使用$parse或$eval方法。

在Direcitve的呈現(xiàn)方面和以前一致:

<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);
//運(yùn)行時(shí)賦值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都是用來(lái)解析表達(dá)式的, 但是$parse是作為一個(gè)單獨(dú)的服務(wù)存在的。$eval是作為scope的方法來(lái)使用的。

$parse典型的使用是放在設(shè)置字符串表達(dá)式映射在真實(shí)對(duì)象上的值。也可以從$parse上直接獲取到表達(dá)式對(duì)應(yīng)的值。

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,是執(zhí)行當(dāng)前作用域下的表達(dá)式,如:scope.$eval('a+b'); 而這個(gè)里的a,b是來(lái)自 scope = {a: 2, b:3};

看看源碼它的實(shí)現(xiàn)是

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

可以找到它也是基于$parse,不過(guò)它的參數(shù)已經(jīng)被固定為this,就是當(dāng)前的scope,所以$eval只是在$parse基礎(chǔ)上的封裝而已,是一種$parse快捷的API。

相關(guān)文章

最新評(píng)論