Pat Migliaccio
Pat Migliaccio

Reputation: 1070

Directive attribute binding with Bootstrap tooltip

I am having an issue where the ternary operator for the glyphicon class switching works just fine but doesn't seem to work on my custom tooltip directive. It just stays with the default Add Project and won't switch to Update Project. It obviously has something to do with my custom directive. Do I need to force a $digest cycle or add a $watch? I'm relatively new to Angular and would greatly appreciate some assistance on this one.

HTML:

<span class="glyphicon glyphicon-{{ currentproject ? 'arrow-up' : 'plus'}}" 
      ng-click="PostProject(currentproject)" 
      tooltip="{{ currentproject ? 'Update' : 'Add'}} Project">
</span>

Custom Directive:

app.directive('tooltip', function () {
    return {
        restrict: 'A',
        scope: {
            tooltip: '@'
        },
        link: function ($scope, element, attrs, ctrl) {
            $(element).tooltip({
                title: $scope.tooltip
            });
        }
    };
});

Upvotes: 0

Views: 508

Answers (2)

Pat Migliaccio
Pat Migliaccio

Reputation: 1070

With all credit and help going to @hansmaad and based on this, here is the final solution:

$scope.$watch('tooltip', function (newValue, oldValue) {
    $(element)
        .tooltip({
            title: newValue
        })
        .attr('data-original-title', newValue);
})

Upvotes: 0

hansmaad
hansmaad

Reputation: 18905

Yes, you should add a $watch to the tooltip. Angular can't magically call $().tooltip() if the value of the expression changes.

    link: function ($scope, element, attrs, ctrl) {
      $scope.$watch('tooltip', function(newValue) {
          updateTooltip(newValue);
          // this does'nt update the existing bs tooltip:
          // see http://stackoverflow.com/a/9875490/498298
          // $(element).tooltip({ title: newValue });
      });
    }

http://codepen.io/hansmaad/pen/QEWwdw?editors=1010

Upvotes: 1

Related Questions