gpt4 book ai didi

angularjs - 如何编写将表达式绑定(bind)到名称的指令 'ng-let'

转载 作者:行者123 更新时间:2023-12-04 04:51:35 25 4
gpt4 key购买 nike

我想编写一个反射(reflect) ng-repeat 但将名称绑定(bind)到单个变量的指令:

所以不要写这样的东西:

ng-repeat="summary in data.accounts.all.summaryAsArray()"

你可以写这样的东西
ng-let="summary as data.accounts.all.summary();
global.some.info as processSummary(summary);"

在哪里:
data.accounts.all.summaryAsArray() returns [<obj>]

data.accounts.all.summary() returns <obj>

这将如何完成?

如何使用它的一个示例是在您想要过滤、排序和分页数据的情况下,但您还想重用绑定(bind)的步骤
ng-let="berts as data('users.list') | filterBy:select('name'):contains('Bert') | sort:by('date-joined');
groups as berts | subArray:page.perpage:pagecurrent | groupBy:has('fish')
"

然后您可以在子元素中相应地使用页面:
  ng-repeat="g in groups"

or {{bert.length}}

最佳答案

这里的目的是有一个指令,将变量添加到范围。这是链接函数的样子(我还没有测试过,但应该不会太远)。

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

}

编辑:请注意,这不会深入观察作为表达式传递的数组。仅当引用发生变化时。

编辑 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);
});
}

关于angularjs - 如何编写将表达式绑定(bind)到名称的指令 'ng-let',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com