AngularJS中使用$parse或$eval在运行时对Scope变量赋值

本文介绍在AngularJS中如何自定义一个表格Directive,通过示例展示了如何在Scope中定义和运行时赋值变量,以及如何使用$parse或$eval方法进行动态赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在"AngularJS中自定义有关一个表格的Directive"中自定义了一个有关表格的Direcitve,其表格的表现方式是这样的:

 

<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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值