AngularJS中如何使用$parse或$eval在運行時對Scope變量賦值
在"AngularJS中自定義有關一個表格的Directive"中自定義了一個有關表格的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中,還有一種運行時給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);
//運行時賦值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都是用來解析表達式的, 但是$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,是執(zhí)行當前作用域下的表達式,如:scope.$eval('a+b'); 而這個里的a,b是來自 scope = {a: 2, b:3};
看看源碼它的實現(xiàn)是
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
可以找到它也是基于$parse,不過它的參數(shù)已經(jīng)被固定為this,就是當前的scope,所以$eval只是在$parse基礎上的封裝而已,是一種$parse快捷的API。
相關文章
用AngularJS來實現(xiàn)監(jiān)察表單按鈕的禁用效果
本篇文章主要介紹了用AngularJS來實現(xiàn)監(jiān)察表單按鈕的禁用效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-11-11
用angular實現(xiàn)多選按鈕的全選與反選實例代碼
本篇文章主要介紹了用angular實現(xiàn)多選按鈕的全選與反選實例代碼,非常具有實用價值,需要的朋友可以參考下2017-05-05
Angular獲取手機驗證碼實現(xiàn)移動端登錄注冊功能
最近在使用angular來做項目,功能要求實現(xiàn)一是點擊按鈕獲取驗證碼,二是點擊登錄驗證表單。之前用jquery來做項目很好做,使用angular怎么實現(xiàn)呢?其實實現(xiàn)代碼也很簡單的,下面通過實例代碼給大家介紹下,需要的朋友參考下吧2017-05-05
angular.js4使用 RxJS 處理多個 Http 請求
本篇文章主要介紹了angular.js使用 RxJS 處理多個 Http 請求,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
詳解在Angular4中使用ng2-baidu-map的方法
這篇文章主要介紹了在Angular4中使用ng2-baidu-map的方法,本文分步驟給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
詳解Angular路由 ng-route和ui-router的區(qū)別
這篇文章主要介紹了詳解Angular路由 ng-route和ui-router的區(qū)別,分別介紹了兩種路由的用法和區(qū)別,有興趣的可以了解一下2017-05-05
AngularJS實現(xiàn)的獲取焦點及失去焦點時的表單驗證功能示例
這篇文章主要介紹了AngularJS實現(xiàn)的獲取焦點及失去焦點時的表單驗證功能,涉及AngularJS使用ng-blur、ng-focus針對表單事件監(jiān)聽相關操作技巧,需要的朋友可以參考下2017-10-10

