1

tldr;

How would I add an element to an HTML tag using AngularJS?

without element:

<a class=“btn btn-primary” href=“blah.com” adding-element>Foo Bar</a>

with element:

<a ng-disabled="!isChecked" class=“btn btn-primary” href=“blah.com” adding-element>Foo Bar</a>

I am trying to perform DOM manipulation and add the ng-disabled element to my HTML tag on initial page load. I have attempted to do it in the code below based on this example but I am wondering if there is a better/easier way? I would also like it to be removed after page load is completed.

If someone could please explain it or provide a good tutorial/reference on how to accomplish this (preferably with plain vanilla Javascript), I would welcome it. Thanks.

HTML (before DOM Manipulation)

<a class=“btn btn-primary” href=“blah.com” adding-element>Foo Bar</a>

HTML (after DOM Manipulation)

<a ng-disabled="!isChecked" class=“btn btn-primary” href=“blah.com” adding-element>Foo Bar</a>

DIRECTIVE

.directive('AddingElement', function() {
restrict: 'A',
//scope: {
//        ng-disabled: "="
//    },
link: function (scope, el, attrs) {
el = angular.element(‘<a ng-disabled=“!isChecked” class=“btn btn-primary” href=“blah.com” adding-element>’)
element.replaceWith(el);
$compile(el)($scope);
});
1
  • I'm looking into using: tutorialspoint.com/jquery/jquery-dom.htm which suggests using selector.replaceWith( content ). After I test it out, I'll update my question accordingly. Commented Aug 9, 2016 at 1:42

1 Answer 1

1

For jQuery style DOM manipulation use angular.element

to add the attribute you can use element.attr('ng-disabled', '!isChecked') and if you need to remove it element.removeAttr('ng-disabled')

.directive('AddingElement', function() {
restrict: 'A',
 //scope: {
 //        ng-disabled: "="
 //    },
link: function (scope, element, attrs) {
  element.attr('ng-disabled', '!isChecked')
  $compile(el)($scope);
});
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.