如何在角度指令中为ng-repeat预渲染变量?

时间:2013-04-25 19:53:20

标签: angularjs angularjs-directive directive angularjs-ng-repeat

我尝试创建类似网格的可重用指令。我想在控制器中定义数据和操作(编辑,删除......)。

app.controller('MainCtrl', function($scope) {
    $scope.data = [
        {id: 1, name: 'aaa'},
        {id: 2, name: 'bbb'},
        {id: 3, name: 'ccc'},
    ];

    $scope.actions = [
        {label:'edit', href:'#edit/{{row.id}}'},
        {label:'delete', ngClick:'doAction({name:\'delete\', id:row.id})'}
    ];

    $scope.doAction = function (name, id) {
        $scope[name](id);
    }

    $scope.delete = function (row) {
        console.log('deleted' + row.id);
    }
});

问题是如何为ng-repeat预呈现部分指令。

app.directive('list', function () {
    return {
        scope: {
            data: '=',
            actions: '=',
            doAction: '&'
        },
        template:
            '<li ng-repeat="row in data">{{row.name}} ' +
                '<span ng-repeat="action in actions">' +
                    '<a href="{{action.href}}" ng-click="{{action.ngClick}}">' +
                        '{{action.label}}' + 
                    '</a> ' +
                '</span>' +
             '</li> '
    }
});

现在处于行动链接<a href="#edit/{{row.id}}">,但我需要<a href="#edit/1>。 对于删除ng-click不起作用。我尝试使用编译,但我无法做到。你能帮助我吗?可能是动作可能是列表的子指令,问题是一样的。

以下是plunker中的实时模板:http://plnkr.co/edit/O7hXXgQb0Num1xZs5Xrt?p=preview

注意:我知道我可以在ctrl href:'#edit'然后<a href="{{action.href}}/{{row.id}}">中修改操作定义,但这不是很好的解决方案,因为在此指令的其他用法中可能是来自$scope.data的其他参数我可以传递给行动,而不是{{row.id}}

更新示例:添加了ng-click for delete

2 个答案:

答案 0 :(得分:2)

@Langdon,对不起,我没有完整地阅读这个问题。我有另一个答案,如下所列,

@urban_racoons请。如果此解决方案有效,请告诉我。我更改了模板部分并在指令

中添加了一个控制器
app.directive('list', function () {
    return {
            scope: {
                data: '=',
                actions: '='
            },
      controller:function($scope,$interpolate){
        $scope.hrefer = function(action,row ){
          return $interpolate(action.href)({row:row})
        }        
      },
        template: 
        '<li ng-repeat="row in data">{{row.name}} ' +
          '<span ng-repeat="action in actions">' +
            '<a href="{{hrefer(action,row)}}">{{action.label}}</a> ' +
          '</span>' + 
        '</li> '
        }
});

答案 1 :(得分:0)

它有点笨重,但它有效,我认为它足以满足您的需求:

app.controller('MainCtrl', function($scope) {
  $scope.data = [
    {id: 1, name: 'aaa'},
    {id: 2, name: 'bbb'},
    {id: 3, name: 'ccc'},
  ];

  $scope.actions = [
    {label:'edit', href: function(row) { return '#edit/' + row.id;}},
    {label:'delete', href: function(row) { return '#delete/' + row.id;}}
  ];

});

app.directive('list', function () {
    return {
            scope: {
                data: '=',
                actions: '='
            },
            template: 
        '<li ng-repeat="row in data">{{row.name}} ' +
          '<span ng-repeat="action in actions">' +
            '<a href="{{action.href(row)}}">{{action.label}}</a> ' +
          '</span>' + 
        '</li> '

        }
});