AngularJS : Want to disable the link when it clicked once
我有一个列表,列表中的每个项目都是可单击的。
我希望每个项目只能单击一次。
一旦有人单击它,它将被禁用或第二次不可单击。
我的代码就像以下内容:
1 2 3 4 5 6 | <li data-ng-repeat="item in items"> {{item.name}} </li> |
flim的答案几乎可以用,但是由于
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 | <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}} </li> </ul> |
JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function MainCtrl($scope) { $scope.items = [ {id: 1, name: 'foo'}, {id: 2, name: 'bar'} ]; $scope.insertRecord = function(itemId) { alert(itemId + ' clicked (inserting...)'); }; } function addCtrl($scope) { } |
请参见JSFiddle。
在addCtrl
范围内创建哈希
1 | $scope.seenIds = {} |
您的insertRecord(item.id)将首先检查是否已找到该ID。如果有,则什么也不做。
1 2 3 4 5 6 | $scope.insertRecord = function (id) { if (typeof $scope.seenIds[id] ==="undefined") { $scope.seenIds[id] = 1; // do your thing } } |
他们可以单击所有想要的东西,但是除了第一次单击之外什么都不会发生。
如果要在jQuery中附加点击处理程序,则可以使用
1 | $("#whatever").one(insertRecord);//no need to pass a an id as it can be derived within the function |
我不确定Angular是否可以执行此操作。