首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在templateUrl覆盖它之前检索AngularJS伪指令的内部HTML?

如何在templateUrl覆盖它之前检索AngularJS伪指令的内部HTML?
EN

Stack Overflow用户
提问于 2018-04-09 00:09:01
回答 1查看 0关注 0票数 0

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

指令用法:

代码语言:javascript
复制
<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>

以前,我的指令看起来像这样,它的工作

代码语言:javascript
复制
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模板变得杂乱无章,我想将按钮包裹在模板中,而不是在它们之后。所以我重构了我认为更好的指令。

代码语言:javascript
复制
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覆盖之前,我还能如何去获得它的内容?

EN

回答 1

Stack Overflow用户

发布于 2018-04-09 09:15:04

访问iniital html可以$transclude在指令控制器内使用。这是从早期版本稍微改变,所以假设使用1.2

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

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档