1

I have defined a directive in angular.js. That directive has a link function and a controller function, and no template, so all the view is generated in the link function. In the link function I am doing the following:

var button=angular.element("<a>");
button.addClass("ng-click: previousLink();");

//previousLink() is a function defined in the scope.
//I am doing it like that, because before that one I attempted to do:
//button.prop("ng-click", "previousLink()");
//button.text("Previous");
//but for some reason it was showing on html as <a>Next</a>, without adding the property.

It does not work. If I click the button it does nothing. If, instead of doing this in the link function in code I were doing it using a template, it would work. For some reason I need to make some manipulations using jquery in the link function. What should I do? Is there anyway to make this work, or would I have to use both template and link function and combine things there?

1
  • ng-click is not written into markup as a class, it is written as an attribute. If you are going to manipulate the html in a way that you expect angular to interpret it you need to use $compile Commented Sep 13, 2014 at 1:44

1 Answer 1

1

To use $compile you need to follow your existing code with something like:

$compile(button.contents())(scope);

If you want it to be dynamic, you can put this inside a $watch like so:

link: function (scope, ele, attrs) {
  scope.$watch(attrs.yourval, function(html) {
    var button=angular.element("<a>");
    button.addClass("ng-click: previousLink();");
    $compile(button.contents())(scope);
  });
}

$compile attaches the scope (supplied as a parameter) to the html you have defined. This will make your button clicks work properly.

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.