AngularJS中如何使用$parse或$eval在運(yùn)行時(shí)對(duì)Scope變量賦值
在"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)文章
在Angular項(xiàng)目使用socket.io實(shí)現(xiàn)通信的方法
這篇文章主要介紹了在Angular項(xiàng)目使用socket.io實(shí)現(xiàn)通信的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
AngularJs bootstrap搭載前臺(tái)框架——準(zhǔn)備工作
ionic3+Angular4實(shí)現(xiàn)接口請(qǐng)求及本地json文件讀取示例
AngularJS實(shí)現(xiàn)按鈕提示與點(diǎn)擊變色效果
Angular+Ionic使用queryParams實(shí)現(xiàn)跳轉(zhuǎn)頁(yè)傳值的方法
Angular開(kāi)發(fā)實(shí)踐之服務(wù)端渲染

