在angular指令中插入元素之前

时间:2016-05-11 00:27:05

标签: javascript jquery angularjs

这是我的HTML代码:

<div class="row">
  <div ng-if="isLoadingApprovalUrl" class="col-xs-12">
    <div class="text-center"><span class="fa fa-spinner fa-pulse fa-5x fa-fw margin-bottom"></span></div>
  </div>

  <div ng-if="!isLoadingApprovalUrl" class="col-xs-12">
    <div ng-if="isAppApproved" class="alert alert-success">{{'WORKSPACE_APPS.APPROVE_GOOGLE_APPS.SUCCESS' | translate}}</div>
    <div class="alert alert-danger" ng-show="errors.length > 0">
      <ul><li ng-repeat="error in errors">{{error}}</li></ul>
    </div>

    <iframe id="appApprovedId" ng-if="approvalUrl" class="approve-iframe" ng-class="{'app-approved': isAppApproved}" ng-src="{{trustedApprovalUrl}}" iframe-onload></iframe>

    <div ng-if="!isApprovalRequired" class="alert alert-info" translate="WORKSPACE_APPS.APPROVE_GOOGLE_APPS.ALREADY_APPROVED" translate-values="{appTitle: googleApp.title}"></div>
  </div>
</div>

这是我的指示

.directive('iframeOnload', function() {
    return {
      restrict: 'A',
      scope: {
        isRequired: '='
      },
      link: function(scope, elem){
        var spinnerElement = angular.element(' <div ng-if="isApprovalRequired" id="appApprovalSpinner" class="row text-center approve-spinner"><i class="fa fa-spinner fa-pulse fa-5x fa-fw margin-bottom"></i></div>');

       elem.parent().append(spinnerElement) ;

        angular.element('#appApprovalSpinner').addClass('ng-show');
        elem.on('load', function(){
          angular.element('#appApprovalSpinner').addClass('ng-hide');
        });
      }
    };

在iframe标记之后添加了spinnerElement,但我想在iframe标记之前添加spinnerElement,但是无法使其在iframe标记之前添加spinnerElement。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

替换

elem.parent().append(spinnerElement) ;

elem.before(spinnerElement) ;

答案 1 :(得分:1)

当我找到这个答案时,我正在努力解决类似的问题,尝试在带有指令的元素之前插入html。不幸的是,Yin Gang的答案需要使用jquery,而不是带角度的jqlite;所以对于不使用jquery的人来说,这是行不通的。

没有jquery这样做:

.directive('iframeOnload', function() {
  return {
    restrict: 'A',
    scope: {
      isRequired: '='
    },
    link: function(scope, elem, attrs) {
      var spinnerElement = angular.element('<div ng-if="isApprovalRequired" id="appApprovalSpinner" class="row text-center approve-spinner"><i class="fa fa-spinner fa-pulse fa-5x fa-fw margin-bottom"></i></div>');

      elem.parent()[0].insertBefore(spinnerElement[0], elem[0]);

      angular.element('#appApprovalSpinner').addClass('ng-show');
      elem.on('load', function() {
        angular.element('#appApprovalSpinner').addClass('ng-hide');
      });
    }
  };
});