小编典典

在templateUrl覆盖AngularJS指令之前,检索它的内部HTML

angularjs

我有一个指令,用于最近重构的表单验证样板。在扩展之前,请允许我进一步解释该指令。

指令用法:

<form class="form-horizontal" name="personalDetails" validated-form>

    <!-- Pass buttons into form through here -->
    <a href="" class="btn btn-success" 
        data-ng-click="saveDetails()"
        data-ng-disabled="!personalDetails.$valid">Save Changes</a>

</form>

以前,我的指令看起来像这样,并且 有效

app.directive('validatedForm', function($compile, $sce) {
    return {
        restrict: 'A',
        scope: true,
        link: function(scope, element, attrs) {

            var template = //... HTML boilerplate code
            var buttons  = element.html(); // Get contents of element before overriding

            element.html(template + buttons);
            $compile(element.contents())(scope);

        }
    }
});

html模板变得一团糟,我想将按钮包装在模板的“内部”,而不是在按钮之后。因此,我将其重构为我认为更好的指令。

app.directive('validatedForm', ['$compile', '$sce', function ($compile, $sce) {

    var domContent = null;

    return {
        restrict: 'AE',
        scope: true,
        templateUrl: '/Content/ngViews/directives/validated-form.html',
        link: function(scope, element, attrs) {

            // This now returns the contents of templateUrl 
            // instead of what the directive had as inner HTML
            domContent = element.html();

            // Scope
            scope.form = {
                caption: attrs.caption,
                location: 'Content/ngViews/forms/' + attrs.name + '.html',
                buttons: $sce.trustAsHtml(domContent),
                showButtons: !(domContent.replace(' ', '') === '')
            };

        }
    };
}]);

因此,我注意到的是element.html()现在检索templateUrl的内容,而不是我指令的内部HTML的内容。在指令被templateUrl覆盖之前,我还能如何获取指令的内容?


阅读 169

收藏
2020-07-04

共1个答案

小编典典

要访问初始html,可以$transclude在指令控制器内使用。与早期版本相比,此更改略有不同,因此假设使用1.2

controller:function($scope,$transclude){
      $transclude(function(clone,scope){
        /* for demo am converting to html string*/
         $scope.buttons=angular.element('<div>').append(clone).html();
      });

    }

**[DEMO](http://plnkr.co/edit/tArVj75kcE6atfjyhnK3?p=preview)**

2020-07-04