简体   繁体   English

AngularJS:单击一次后要禁用该链接

[英]AngularJS : Want to disable the link when it clicked once

I have a list and each item of the list is clickable. 我有一个列表,列表中的每个项目都是可单击的。

I want that each item should be clickable only one time. 我希望每个项目只能单击一次。

Once someone click on it, it will be disable or not clickable for second time. 一旦有人单击它,它将被禁用或第二次不可单击。

My code is Like folowing: 我的代码如下所示:

<li data-ng-repeat="item in items">
  <a id="{{item.id}}" data-ng-click="insertRecord(item.id)" data-ng-controller="addCtrl">
  {{item.name}}
  </a>
</li>

flim's answer almost works but since addCtrl creates isolate scope, you would need to define seenIds on the scope whose controller contains addCtrl . 弗利姆的答案几乎工作,但因为addCtrl创建隔离范围,你就需要定义seenIds在其控制器包含范围addCtrl Here is a working solution: 这是一个可行的解决方案:

The HTML: HTML:

<div ng-app ng-controller="MainCtrl">
  <ul>
    <li data-ng-repeat="item in items">
      <a id="{{item.id}}" data-ng-controller="addCtrl"
          data-ng-click="item.clicked || insertRecord(item.id); item.clicked = true">
      {{item.name}}
      </a>
    </li>
  </ul>
</div>

The JS: JS:

function MainCtrl($scope) {
    $scope.items = [
        {id: 1, name: 'foo'},
        {id: 2, name: 'bar'}
        ];

    $scope.insertRecord = function(itemId) {
        alert(itemId + ' clicked (inserting...)');
    };
}

function addCtrl($scope) {
}

See on JSFiddle . 参见JSFiddle

If you were to attach the click handler in jQuery, then you could use .one() , for example : 如果要在jQuery中附加点击处理程序,则可以使用.one() ,例如:

$("#whatever").one(insertRecord);//no need to pass a an id as it can be derived within the function

I'm not sure Angular allows you to do this. 我不确定Angular是否可以执行此操作。

Create a hash in the scope of addCtrl 在addCtrl范围内创建哈希

$scope.seenIds = {}

Your insertRecord(item.id) will check first if the id has been seen. 您的insertRecord(item.id)将首先检查是否已找到ID。 If it has, don't do anything. 如果有,什么也不做。

$scope.insertRecord = function (id) {
  if (typeof $scope.seenIds[id] === "undefined") {
    $scope.seenIds[id] = 1;
    // do your thing
  }
}

They can click all they want, but nothing will happen except the first click. 他们可以单击所有想要的东西,但是除了第一次单击之外什么都不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM