4

我尝试创建像网格这样的可重用指令。我想在控制器中定义数据和操作(编辑、删除……)。

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 以删除

4

2 回答 2

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> '
        }
});
于 2013-04-25T20:16:20.030 回答
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> '

        }
});
于 2013-04-25T20:49:50.457 回答