这里的目的是有一个指令将变量添加到作用域。这是链接函数的样子(我还没有测试过,但应该不会相差太远)。
scope: false,
transclude: 'element',
link: function($scope, $element, $attr) {
// We want to evaluate "(variable) as (expression)"
var regExp = /^\s*(.*)\s+as\s+(.*)\s*/,
match = $attr.ngLet.match(regExp);
if(!match) return; // Do nothing if the expression is not in a valid form
var variableName = match[1],
expression = match[2],
assign = function(newValue) { $scope[variableName] = newValue; }
// Initialize the variable in the scope based on the expression evaluation
assign($scope.$eval(expression));
// Update when it changes
$scope.$watch(expression, assign);
}
Edit:请注意,这不会深入观察作为表达式传递的数组。仅当参考发生变化时。
Edit 2:为了允许多个定义,可以进行一些小的调整:
scope: false,
transclude: 'element',
link: function($scope, $element, $attr) {
// We want to evaluate "(variable) as (expression)"
var regExp = /^\s*(.*)\s+as\s+(.*)\s*/;
angular.forEach($attr.ngLet.split(';'), function(value) {
var match = value.match(regExp);
if(!match) return;
var variableName = match[1],
expression = match[2],
assign = function(newValue) { $scope[variableName] = newValue; };
// Initialize the variable in the scope based on the expression evaluation
assign($scope.$eval(expression));
// Update when it changes
$scope.$watch(expression, assign);
});
}