A table-related direcitve is customized in the "Angularjs custom about a table" in "Directive", and its form behaves as follows:
<table-helper datasource= "Customers"
clumnmap= [{name: ' name '}, {street: ' street '}, {age: ' age '}, {url: ' url ', hidden : true}] "></table-helper>
Above, the value of the variable colmnmap is defined in the scope in advance:
return {
restrict: ' E ',
scope: {
columnmap: ' = ',
datasource: ' = '
},
Link:link,
template : template
In Angularjs, there is also a way to assign a value to a scope variable at run time, which is to use the $parse or $eval method in the link function .
Consistent with previous direcitve rendering:
<table-helper-with-parse datasource= "Customers" columnmap= [{name: ' name '},...] " ></table-helper-with-parse>
Directive is roughly like this:
var tablehelperwithparse = function ($parse) {
var template = "",
link = function (scope, element, attrs) {
var h Eadercols = [],
tablestart = ' <table> ',
tableend = ' </table> ',
table = ',
visibleprops = [] ,
Sortcol = null,
Sortdir = 1,
columnmap = null;
$scope. $watchCollection (' datasource ', render);
Runtime Assignment Columnmap
Columnmap = scope. $eval (ATTRS.COLUMNMAP);
or
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);
Here's a description of the difference between $parse and $eval.
First of all, $parse and $eval are used to parse expressions, but $parse exist as a separate service. $eval is used as a method of scope.
$parse Typical use is to place a value on the set string expression that is mapped to a real object. You can also get the value of an expression directly from the $parse.
var getter = $parse (' User.Name ');
var setter = getter.assign;
Setter (scope, ' new name ');
Getter (context, locals)//pass-through scope, return value
setter (scope, ' new name ')//Modify the value of the property mapped on scope to ' new value '
$eval is scope. $eval is the execution of an expression under the current scope, such as scope. $eval (' a+b '); And the a,b in this is from scope = {a:2, b:3};
Look at the source code its implementation is
$eval: function (expr, locals) {return
$parse (expr) (this, locals);
Can find it is also based on $parse, but its parameters have been fixed to this, is the current scope, so $eval just on the $parse based on the encapsulation, is a $parse fast API.