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

标签 javascript 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 覆盖之前获取指令的内容?

最佳答案

要访问初始 html,可以在指令 Controller 中使用 $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

关于javascript - 在 templateUrl 覆盖它之前检索 AngularJS 指令的内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110927/

相关文章:

javascript - 如何将输入值作为参数传递到 Angularjs 中的自定义过滤器中

javascript - 如何将此类对象的此类数组传递给 JS?

javascript - 如何使用 Javascript 更改隐藏字段数组而不丢失其正确格式?

javascript - 为什么我的 for 循环不能迭代基本对象?

javascript - Jquerymobile过滤器 ListView 在动态获取数据时不起作用

javascript - 无法访问 Jasmine 测试用例中的范围变量

javascript - 在 React Native 中将 props 样式添加到现有组件样式

angularjs - 在特定位置禁用 ng-touch

javascript - 如何在 api 的链式执行期间制作 frisby.js 脚本 "pause"

angularjs - 在数组中的每个元素上设置 $scope.$watch