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

时间:2013-06-28 01:22:31

标签: angularjs

我想编写一个反映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}}

1 个答案:

答案 0 :(得分: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);
    });
}