如何编写将表达式绑定到名称的指令“ng-let”

2024-03-08

我想编写一个镜像 ng-repeat 但将名称绑定到单个变量的指令:

所以不要写这样的东西:

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

你可以写这样的东西

ng-let="summary as data.accounts.all.summary();
        global.some.info as processSummary(summary);"

where:

data.accounts.all.summaryAsArray() returns [<obj>]

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

这将如何完成?


举例说明如何使用此功能的情况是,您想要对数据进行筛选、排序和分页,但还希望重用绑定的步骤

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')
       "

然后您可以在子元素中相应地使用 page :

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

}

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);
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何编写将表达式绑定到名称的指令“ng-let” 的相关文章

随机推荐