AngularJS:在ng-repeat中保存所选行的单击操作

时间:2017-02-11 09:30:48

标签: javascript angularjs hyperlink angularjs-ng-repeat

摘要:

我在 array of objects 列表中显示 ng-repeat 。每个对象都有三个属性idname& agename字段是可点击的。

enter image description here

要求:

用户点击name字段 <a> 标记后,应从表中删除已点击的特定记录。

假设我点击Alpha,则应从此字段中删除链接。

enter image description here

问题陈述:

假设用户先前点击了Alpha,现在他将点击Beta。然后,Alpha字段的状态再次更改为之前的状态(已添加<a>标记。)

enter image description here

删除<a>标记后,不应再为该特定字段添加标记。

我到目前为止尝试过:

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

function PeopleCtrl($scope, $http) {

$scope.people = [
    {
    id: 1,
    name: "Alpha",
    age: "24"
    },
{
    id: 2,
    name: "Beta",
    age: "25"
    }
];

$scope.removeLink = function(index) {
  $scope.rowIndex = index;
};

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PeopleCtrl">
<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td>
        <td ng-show="rowIndex != $index">
        <a href="" ng-click="removeLink($index)">{{person.name}}         </a>
        </td>
        <td ng-show="rowIndex == $index">
          {{person.name}}
        </td>
        <td>{{person.age}}</td>
    </tr>
</table>
</div>

1 个答案:

答案 0 :(得分:1)

更好的处理方法是让 field 为超链接为true或false,点击后将其设为 true ,< / p>

<强>样本

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

function PeopleCtrl($scope, $http) {

$scope.people = [
    {
    id: 1,
    name: "Alpha",
    age: "24",
    clicked : false
    },
{
    id: 2,
    name: "Beta",
    age: "25",
    clicked : false
    }
];

$scope.removeLink = function(person) {
 person.clicked = true;
};

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PeopleCtrl">
<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td>
        <td ng-if="!person.clicked">
        <a href="" ng-click="removeLink(person)">{{person.name}}         </a>
        </td>
        <td ng-if="person.clicked">
          {{person.name}}
        </td>
        <td>{{person.age}}</td>
    </tr>
</table>
</div>