angularjs - How does $parse work? -
i have simple code this:
<div ng-app="app"> <input type="text" ng-model="money" mask="2"> <p>{{money}}</p> </div> angular.module("app", []) .directive("mask", function($parse) { return { restrict: "a", require: "ngmodel", link: function(scope, element, attrs) { console.log($parse(attrs.mask)); // function(s, l, a, i){return 2;} console.log($parse(attrs.mask)(scope)); // 2 } } }); why first output function(s, l, a, i){return 2;}with (s, l, a, i)?
in case need jsfiddle: https://jsfiddle.net/ealonwang/x1hcbpjw/11/
according angular documentation $parse service
$parse() without calling scope iief, returns function evaluated expession, aka: return 2;
however function returned takes multiple arguments:
function(context, locals) function represents compiled expression:
context – {object} – object against expressions embedded in strings evaluated against (typically scope object). locals – {object=} – local variables context object, useful overriding values in context.
the returned function has following properties:
literal – {boolean} – whether expression's top-level node javascript literal. constant – {boolean} – whether expression made entirely of javascript constant literals. assign – {?function(context, value)} – if expression assignable, set function change value on given context.
so seeing evaluated not invoked function being returned service.
listed below test cases ran against service explain how locals , context used , defined:
var getter = $parse('user.name'); var setter = getter.assign; var context = {user:{name:'angular'}}; var locals = {user:{name:'local'}}; expect(getter(context)).toequal('angular'); setter(context, 'newvalue'); expect(context.user.name).toequal('newvalue'); expect(getter(context, locals)).toequal('local'); specifically arguments mean found here: https://github.com/angular/angular.js/blob/master/src/ng/parse.js#l1934
var value = parsedexpression(scope, locals, assign, inputs);
Comments
Post a Comment