简体   繁体   中英

DOM Manipulation Adding an Element in AngularJS

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);
});

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM