Angularjs cookbook

Page 19

Show a confirm box before ng-click is executed

11

For this to works, we bind the element to the click event and create a new box and disable the butotn when its clicked. The box itself has a new scope with two functions ok() and cancel(). If we click ok() we trigger the original click event. On cancel() we close the box an reenable the button. 1 2 3 4 5 6 7 8 9 10 11 12

angular.module('cookbookApp', []) .directive('confirmedClick', function($parse, $q, $compile, $rootScope) { var box = '<div class="box"><div>Really?</div> ' + '<button ng-click="close($event, true)">OK</button>' + '<button ng-click="close($event)">Cancel</button>' + '</div>'; return { link: function(scope, element, attrs) { var fn = $parse(attrs.confirmedClick); element.on('click', function() { var boxScope = $rootScope.$new(); var boxElement = $compile(box)(boxScope);

13

element.attr('disabled', 'disabled'); element.append(boxElement);

14 15 16

boxScope.close = function(event, execute) { event.stopPropagation(); element.removeAttr('disabled'); boxElement.remove(); if (execute) { fn(scope, {$event: event}); } }; });

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

} }; }) .controller('MainController', function($scope) { $scope.tasks = ['Tidy up', 'Wash the dishes']; $scope.removeTask = function(index){ $scope.tasks.splice(index, 1); }; });

For the style we give the directive element a relative position, so that we can place the box we show absolute to it:


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.