AngularJS中使用$parse或$eval在執行時對Scope變數賦值

Darren Ji發表於2016-01-25

 

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

 

相關文章