My AngularJS template contains some custom HTML syntax like:
<su-label tooltip="{{field.su_documentation}}">{{field.su_name}}</su-label>
I created a directive to process it:
.directive('suLabel', function() { return { restrict: 'E', replace: true, transclude: true, scope: { title: '@tooltip' }, template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>', link: function(scope, element, attrs) { if (attrs.tooltip) { element.addClass('tooltip-title'); } }, } })
Everything works fine, at the exception of the attrs.tooltip
expression, which always returns undefined
, even though the tooltip
attribute is visible from Google Chrome's JavaScript console when doing a console.log(attrs)
.
Any suggestion?
UPDATE: A solution was offered by Artem. It consisted in doing this:
link: function(scope, element, attrs) { attrs.$observe('tooltip', function(value) { if (value) { element.addClass('tooltip-title'); } }); }
AngularJS + stackoverflow = bliss
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior. In summary, an attribute directive changes the appearance or behavior of a DOM element.
Directives are markers on the DOM element which tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives.
The ng-transclude directive facilitates AngularJS to capture everything that is put inside the directive in the markup and use it somewhere in the directive's template.
See section Attributes from documentation on directives.
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With