在删除按钮上改进“alert()”

时间:2016-10-09 09:23:27

标签: angularjs

我有一个角度应用程序,其中包含几个删除按钮,如下所示:

<button class="btn btn-default" ng-click="delete($index)">x</button>

现在我们正在接近生产部署,我希望删除按钮表现得很好,并且在实际删除对象之前“警告()”用户。

如何通过指令在所有删除按钮中改编此功能。我想要一个名为“ask”的指令:

<button ask class="btn btn-default btn-xs" ng-click="delete($index)">x</button>

我可以用它来影响任何按钮的行为。

不知怎的,我无法思考这个

app.directive("ask", function() {
  return function(scope, elems, attrs) {
    // what to do here:
    // 1. shall I change the elems.attr("ng-click")
    // 2. or scope.attrs("ngClick")
    ????
  }
});

请指导我最佳做法和一些代码示例。另请注意,所有删除按钮的ng-click回调都不同,应用程序已经广泛使用了隔离范围和子范围指令。

2 个答案:

答案 0 :(得分:1)

尝试此实现

&#13;
&#13;
angular
  .module('test', [])
  .directive('ask', function() {
    return {
      restrict: 'A',
      scope: {ask: '@', onAsk: '&'},
      link: function(scope, elem, attrs) {
        elem.on('click', function(e) {
          if(confirm(attrs.ask)) {
            scope.onAsk();
            scope.$apply();
          }
        });
      }
    };
  })
  .controller('ItemsCtrl', function($scope) {
    $scope.items = [1,2,3,4,5];
    $scope["delete"] = function(index) {
      $scope.items.splice(index, 1);
     };
  })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="ItemsCtrl">
  <ul><li ng-repeat="item in items track by $index">{{item}}
  <button ask="Are you sure you want to delete item?" on-ask="delete($index)">x</button>
    </li>
    </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以为此directive template directivebutton元素和ng-click事件构建index

deleteapp.directive("deleteFruit", function(){ return{ // You can also pass one more binding if you want to have a specific alert message scope:{ index: '@', delete:'&' }, template:'<button class="btn btn-default" ng-click="deleteFruit()">x</button>', link: function(scope){ scope.deleteFruit = function(){ // When user clicks, first call the alert function then use the promise returned by dialog and check whether user wants to delete or not //modal.dialog().then(function(userSelectedOption){ // If user wants to delete then go a head and call delete function on main controller // if(userSelectedOption){ // scope.delete(scope.index); // } //}) scope.delete(scope.index); } } } }) 函数作为此指令的输入。

 <delete-fruit delete="delete(index)" index={{$index}}></delete-fruit>

MainCtrl HTML

self.imageview1 = [UIImage  dataWithContentsOfURL@"http://www.fnordware.com/superpng/pnggrad16rgb.png"];

Plunker