AngularJS: ng-src behavior on non-standard attributes?

前端 未结 4 1465
温柔的废话
温柔的废话 2021-02-13 03:17

I\'m integrating a media player in my app using the \"Video For Everybody\" generator. As the player features a fallback to flash if the browser doesn\'t support HTML5 vid

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 03:34

    Finding the source of build-in directive is made easy on the official API documentation. In this case go to the documentation of ngSrc , at the top of the page you will see two buttons, "Improve this doc" and "View source", click on "View source" and it will automatically take you to the correct source file where the directive is defined. This works across all build-in directive, very handy!

    Below I'm pasting the code for ngSrc, which interestingly enough does not look complicated at all, the crucial line seems to be priority: 99, based on the comment next to it means that directives with priority of 99 will run after attributes have been interpolated.

    // ng-src, ng-srcset, ng-href are interpolated
    forEach(['src', 'srcset', 'href'], function(attrName) {
      var normalized = directiveNormalize('ng-' + attrName);
      ngAttributeAliasDirectives[normalized] = function() {
        return {
          priority: 99, // it needs to run after the attributes are interpolated
          link: function(scope, element, attr) {
            attr.$observe(normalized, function(value) {
              if (!value)
                 return;
    
              attr.$set(attrName, value);
    
              // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
              // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
              // to set the property as well to achieve the desired effect.
              // we use attr[attrName] value since $set can sanitize the url.
              if (msie) element.prop(attrName, attr[attrName]);
            });
          }
        };
      };
    });
    

    Given the above it should be trivial to implement your own directive.

提交回复
热议问题