WhoDidThis
WhoDidThis

Reputation: 383

Adding an ng-element dynamically

If I wanted to add a dynamically created ng-href to an element how can I get it to behave like a usual ng-href?

<a test-href="/link">Test link</a>

Directive:

app.directive("testHref", function() {
  return {
    link: function(scope, elem, attr) {
      var newlink = attr.dbHref + "/additional/parameters";
      attr.$set("ng-href", newlink);
    }
  };
});

This produces <a test-href="/link" ng-href="/link/additional/parameters">Test link</a>, but how can I also get the ng-href to behave as it should?

Upvotes: 0

Views: 1238

Answers (4)

Rubi saini
Rubi saini

Reputation: 2535

If you want to bind a dynamic url with href then you can manipulate you URL in ng-click or ng-mousedown event and bind to target element.

JS:

var goToDetailPage = function (event, id) {
    var newState = $state.href('DetailView', {id: id});
    jQuery(event.target).attr('href',newState);
};

HTML:

<a ng-mousedown="goToDetailPage($event, id)"> Click Here </a>

Upvotes: 0

erandac
erandac

Reputation: 575

I don't think you need to write a custom directive to have a dynamic url for href. You could use ng-href and the scope-parameter bindings.

<a ng-href="/path/{{dynamic_var_on_scope}}/123/?p={{var2}}"> Click Here </a>

Upvotes: 0

Banana-In-Black
Banana-In-Black

Reputation: 2557

http://jsfiddle.net/UnpSH/

app.directive("testHref", function($compile) {
  return {
    link: function(scope, elem, attr) {
      var newlink = attr.dbHref + "/additional/parameters";
      attr.$set("ng-href", newlink);
      elem.removeAttr('test-href'); // prevent recursion
      $compile(elem)(scope); // compile it again
    }
  };
});

Not sure what you want to achieve, but you should use something like ng-href = "/path/{{scopeVariable}}" for dynamically changing your link.

Upvotes: 2

jd4u
jd4u

Reputation: 5807

You can bind ng-href to your object's dynamic Url property like ng-href="{DynamicUrl}"

http://docs.angularjs.org/api/ng.directive:ngHref

If you are building a directive that require to add dynamically angulerjs directives, you shall use $compile to get appropriate result.

Upvotes: 1

Related Questions