2

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

所以不要写这样的东西:

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>

这将如何完成?


如何使用它的一个示例是在您想要过滤、排序和分页数据的情况下,但您还想重用绑定的步骤

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}}
4

1 回答 1

3

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

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);
    });
}
于 2013-06-28T01:54:21.617 回答