Accessing attributes from an AngularJS directive

前端 未结 2 959
死守一世寂寞
死守一世寂寞 2020-11-28 03:01

My AngularJS template contains some custom HTML syntax like:

{{field.su_name}}


        
相关标签:
2条回答
  • 2020-11-28 03:15

    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.

    0 讨论(0)
  • 2020-11-28 03:22

    Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

    <su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
    

    Directive:

    myApp.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 (scope.title) {
                    element.addClass('tooltip-title');
                }
            },
        }
    });
    

    Fiddle.

    With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

    0 讨论(0)
提交回复
热议问题