Reputation: 1412
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);
});
Upvotes: 1
Views: 260
Reputation: 1402
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);
});
Upvotes: 1