Search code examples
javascriptjqueryangularjsbootbox

angular.js template variables to bootbox dialog?


I've been trying to figure this out for like 10 hours now. Time to ask for help!

I'm trying to pass a variable from an angular.js template variable to bootbox for a nice looking confirmation prompt.

Assume that I have the following (abbreviated for clarity):

<script>
      $(document).on("click", ".confirm", (function(e) {
        e.preventDefault();
        bootbox.confirm("This needs to be the value of {{item.name}}", function(confirmed) {
          console.log("Confirmed: "+confirmed);
        });
      }));
</script>

which is executed as such:

<ul class="list-group">
    <li ng-repeat="item in items">
         <a href="" class="confirm"><span class="glyphicon glyphicon-fire red"></span></a>
    </li>
</ul>

When the user clicks the link, I would like a the confirmation box to appear, and I need to include attributes like {{item.name}} and {{item.row}} that are specific to this element in the list.

I have read up on the $compile functionality of angular.js and I got it working in so far as having a <div compile="name"> but that doesn't help me for retrieving a single entry out of my list as I am iterating. Any help would be appreciated!


Solution

  • Applied as a directive...

    HTML:

    <body ng-app="myApp" ng-controller="MainController">
      <ul class="list-group">
        <li ng-repeat="item in items">
             <confirm-button name="{{item.name}}"></confirm-button>
        </li>
      </ul>
    </body>
    

    JS:

    angular.module('myApp', [])
    .controller('MainController', function($scope) {
      $scope.items = [
        { name: 'one' },
        { name: 'two' },
        { name: 'three' }
      ];
    })
    .directive('confirmButton', function(){
      return {
        restrict: 'E',
        scope: { name: '@' },
        template: '<a href="#" class="confirm"><span class="glyphicon glyphicon-fire red" ng-click="confirm(name)">Button</span></a>',
        controller: function($scope) {
          $scope.confirm = function(name) {
            bootbox.confirm("The name from $scope.items for this item is: " + name, function(result){
              if (result) {
                console.log('Confirmed!');
              } else {
                console.log('Cancelled');
              }
            });
          };
        }
      }
    });
    

    Working plunk