Dynamic Bootstrap Tooltip
I was working on an angular application. There I got a requirement to show bootstrap tooltip whose content(title) change dynamically. Following is the way I generally use to show the bootstrap tooltip:
1 2 3 4 5 6 7 8 9 |
[code] <a href="#" data-toggle="tooltip" title="Default">Hover Over Me</a> <script type="text/javascript"> $(function(){ $('a[data-toggle="tooltip"]').tooltip(); }); </script> [/code] |
Above approach works fine. So I use this approach with dynamic data as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
[code] <div ng-app='MyModule' ng-controller="MyController" style="margin: 20px"> <input ng-model="myData" />{{myData}} <br/><br/> <a data-toggle="tooltip" title="{{myData}}">Hover Over Me</a> </div> <script type="text/javascript"> $(function(){ $('a[data-toggle="tooltip"]').tooltip(); }); var app = angular.module('MyModule', []); app.controller('MyController', function ($scope) { $scope.myData = "Default"; }); </script> [/code] |
but this is not working. Each time “Default” is shown in the tooltip even if I change the angular variable data.
Solution of this issue is quite simple just replace “title” with “data-original-title” and code runs fine:
1 2 3 4 5 6 |
[code] <div ng-app='MyModule' ng-controller="MyController" style="margin: 20px"> <input ng-model="myData" />{{myData}} <br/><br/> <a data-toggle="tooltip" data-original-title="{{myData}}">Hover Over Me</a> </div> [/code] |
At the time of DOM loading the two chunks of codes (initializing the tooltip and angular stuff) runs independently and separately which can cause race condition in a complex scenario. In that case you can use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[code] <div ng-app='MyModule' ng-controller="MyController" style="margin: 20px"> <input ng-model="myData" />{{myData}} <br/><br/> <a data-toggle="tooltip" data-original-title="{{myData}}">Hover Over Me</a> </div> <script type="text/javascript"> var app = angular.module('MyModule', []); app.controller('MyController', function ($scope) { $('a[data-toggle="tooltip"]').tooltip(); $scope.myData = "Default"; }); </script> [/code] |
Hope this helps 🙂 .
And if you want any further information regarding software development, please click here
I don’t know how or why but this works! Thank you.