Dynamically add angular attributes to an element from a directive

后端 未结 1 725
谎友^
谎友^ 2021-02-02 15:19

I\'m trying to build a directive that change loading status on buttons for slow ajax calls. Basically the idea is to set an attribute \"ng-loading\" to a button element, and let

相关标签:
1条回答
  • 2021-02-02 15:25

    You don't need to recompile that directive if all you want is some DOM manipulation, you can add and remove class in regards to the changes of a scope property. You can use $watch instead.

    JAVASCRIPT

    .directive('ngLoading', function() {
      return function(scope, element, attrs) {
        var img = angular.element('<img class="loading-icon" src="/assets/images/loading-icon.gif"/>');
        element.append(img);
        scope.$watch(attrs.ngLoading, function(isLoading) {
           if(isLoading) {
             img.removeClass('ng-hide');
             element.addClass('loading');
             element.attr('disabled', '');
           } else {
             img.addClass('ng-hide');
             element.removeClass('loading');
             element.removeAttr('disabled');
           }
        });
      };
    });
    

    Note: Your code doesn't work because it compiles the contents of the elements, not the element itself, where you attach the attributes you have implemented.

    try $compile(elem)(scope); and it should work properly, but I don't recommend it because each element with such directive will have to re-compile again.

    UPDATE: before using $compile remove the attribute 'ngLoading' to the element to prevent infinite compilation.

    elem.removeAttr('ng-loading');
    $compile(elem)(scope);
    
    0 讨论(0)
提交回复
热议问题