如何针对ng-repeat中的特定项目定位ng-show?

时间:2015-04-01 16:41:16

标签: angularjs angularjs-ng-repeat angular-ngmodel

http://plnkr.co/edit/aiGCPJEwTj0RWnuoCjsW?p=preview

我希望删除按钮仅显示该项的弹出窗口。

你会怎么做? HTML:

<li ng-repeat="acc in accounts">
    <div class="well well-sm">
        <div class="popover-remove" ng-show="popoverRemove">Click to remove item</div>
        <h4>{{acc.label}}</h4>
        <button class="btn btn-default"
                ng-mouseover="showPopover()"
                ng-mouseleave="hidePopover()">Remove</button>
    </div>
</li>

角度控制器:

    var app = angular.module('myApp', [])

.controller('AccountsCtrl',
    ['$scope',
    function($scope) {

    var vs = $scope;

        vs.accounts = [
            {
                id: '1',
                label: 'Bitage'
            },
            {
                id: '2',
                label: 'Blockchain.info'
            },
            {
                id: '3',
                label: 'Coinbase wallet'
            },
            {
                id: '4',
                label: 'Xapo wallet'
            }
        ];

        vs.showPopover = function() {
            vs.popoverRemove = true;
        };

        vs.hidePopover = function() {
            vs.popoverRemove = false;
        };

    }]);

enter image description here

3 个答案:

答案 0 :(得分:4)

Plunker为你

问题是ng-repeat创建了它自己的范围。因此,'popoverRemove'是每个范围的局部变量。您可以通过向ng-repeat的特定元素的控制器发送上下文来将true或false设置为局部变量并使用'this'设置它的值。

<button class="btn btn-default"
                    ng-mouseover="showPopover(this)"
                    ng-mouseleave="hidePopover(this)">Remove</button>

vs.showPopover = function(context) {
    context.popoverRemove = true;
};

vs.hidePopover = function(context) {
    context.popoverRemove = false;
};

答案 1 :(得分:2)

您还可以在每次迭代中创建一个属性,如下所示:

我没有在范围内调用函数,而只是将well.show的值设置为true / false,但是你得到了这个想法的主旨!

    <li ng-repeat="acc in accounts track by $index">
      <div class="well well-sm">
        <div class="popover-remove" ng-show="well.show">Click to remove item</div>
        <h4>{{acc.label}}</h4>
        <button class="btn btn-default"
                ng-mouseover="well.show=true"
                ng-mouseleave="well.show=false">Remove</button>
      </div>
    </li>

Plunker updated

答案 2 :(得分:1)

将popOverRemove移动到每个帐户。然后,您可以从每个子范围控制它。同时更新你的showPopover / hidePopover。

vs.accounts = [
    {
        id: '1',
        label: 'Bitage',
        popoverRemove: false
    },
    {
        id: '2',
        label: 'Blockchain.info',
         popoverRemove: false
    },
    {
        id: '3',
        label: 'Coinbase wallet',
       popoverRemove: false
    },
    {
        id: '4',
        label: 'Xapo wallet',
        popoverRemove: false
    }
];

我已在此处更新

http://plnkr.co/edit/uAjhiYTDyXIBmkxAQzzw?p=preview