0

How do I replace an Angular attribute that already has a value in it? For example:

angular.module('app', [])
.directive('edit', function(){
  return {
    template: '<a ng-href="{{data}}">Link Text</a>',
    replace: true,
    link: function(scope, elm, attr){
      scope.data = 'http://www.example.com';
    }
  };
});

HTML:

<a edit ng-href="test"></a>

That just appends the link url to the "test" href. I tried using

elm.attr('ng-href', '{{data}}');

and many variations on that idea, but it didn't work.

2
  • are you asking this for any directive or specially for ngHref? Commented Apr 2, 2014 at 6:39
  • Can you show this in a plunkr and explain in the comments what you see vs what you expect... also explaining the higher level goal might help to get a better solution since there are various ways to define directives or organize things. Commented Apr 2, 2014 at 6:43

1 Answer 1

1

You can use compile function in directive, and redeclare this attribute in it:

.directive('edit', ['$timeout', function($timeout) {
   return {
      template: '<a ng-href="{{data}}">Link Text</a>',
      replace: true,
      restrict:'A',
      compile:function(elm, attr){
        return {
          pre: function preLink(scope, iElement, iAttrs, controller) { 
             iAttrs.ngHref = "{{data}}";
          },
          post: function postLink(scope, iElement, iAttrs, controller) {
            scope.data = 'http://www.example.com';
          }
        }

      }
    }
  }])

http://plnkr.co/edit/lBA9xR1VbWHqHbc5KG7w?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.