This article mainly introduces how to use $ parse or $ eval in AngularJS to assign values to the Scope variable at runtime. This article is very detailed and has reference value, you can refer to "customizing Directive for a table in AngularJS" to customize a Direcitve for a table. The table is displayed as follows:
Above, the value of the variable colmnmap is defined in Scope beforehand:
return {restrict: 'E',scope: {columnmap: '=',datasource: '='},link:link,template:template};
In AngularJSOne way to assign values to the Scope variable at runtime is to use the $ parse or $ eval method in the link function..
The presentation of Direcitve is consistent with the previous one:
Directive is roughly like this:
Var tableHelperWithParse = function ($ parse) {var template = "", link = function (scope, element, attrs) {var headerCols = [], tableStart ='
', Table = '', visibleProps = [], sortCol = null, sortDir = 1, columnmap = null; $ scope. $ watchCollection ('datasource ', render); // value columnmapcolumnmap = scope during runtime. $ eval (attrs. columnmap); // or columnmap = $ parse (attrs. columnmap) (); wireEvents (); function rener () {if (scope. datasource & scope. else se. length) {table + = tableStart; table + = renderHeader (); table + = renderRows () + tableEnd; renderTable () ;}}; return {restrict: 'E ', scope: {datasource: '='}, link: link, template: template} angular. module ('citcitvesmodule '). directive ('tablehelperwithparse', tableHelperWithParse );
Next we will introduce the differences between $ parse and $ eval.
First, both $ parse and $ eval are used to parse expressions, but $ parse exists as a separate service. $ Eval is used as the scope method.
$ Parse is typically used to set the value of a string expression mapped to a real object. You can also obtain the value corresponding to the expression from $ parse.
Var getter = $ parse ('user. name '); var setter = getter. assign; setter (scope, 'new name'); getter (context, locals) // input scope, return value setter (scope, 'new name ') // modify the attribute value mapped to the scope to 'new value'
$ Eval is scope. $ eval is the expression used to execute the current scope, such as scope. $ eval ('a + B '); in this case, a and B are from scope = {a: 2, B: 3 };
Let's look at the Source Code. Its implementation is
$eval: function(expr, locals) {return $parse(expr)(this, locals);},
It can be found that it is also based on $ parse, but its parameter has been fixed to this, which is the current scope, so $ eval is only encapsulated on the basis of $ parse, is a quick API for $ parse.