angularjs - 在渲染模板之前编译指令

标签 angularjs angularjs-directive angularjs-compile

我正在为 Angular 状态选择制定指令。它可以工作,但我花了一些时间试图找到一种在 DOM 中之前编译模板的方法。目前它的工作原理如下:

 app.register.directive('stateDropdown', ['StatesFactory', '$compile', function (StatesFactory, $compile) {
        function getTemplate(model) {
            var html = '<select ng-model="' + model + '" ng-options="state.abbreviation as state.name for state in states" class="form-control"></select>';
            return html;
        }

        function link (scope, element, attrs) {
            scope.states = StatesFactory.States;
            element.html(getTemplate(attrs.stateModel));
            $compile(element.contents())(scope);
        }
        return {
            replace: true,
            link: link

        }
    }]);

但因此它将模板插入到元素中,然后根据范围对其进行编译。有一个更好的方法吗?例如在插入模板之前对其进行编译?

最佳答案

从我以前拥有的东西开始。

[编辑2]

使用动态模型试图将其融入正常的 Angular 工作流程会有点问题。 相反,您需要手动编译指令中的模板,但在此之前添加 ng-model,您还需要管理使用构建模板替换现有元素。

module.directive('stateDropdown', function (StatesFactory, $compile) {

    var template = '<select ng-options="state.abbreviation as state.name for state in states" class="form-control"></select>';
    return {
        scope: true,
        controller: function($scope) {
            $scope.states = StatesFactory.states;
        },
        compile: function($element, $attrs) {
            var templateElem = angular.element(template).attr('ng-model', '$parent.' + $attrs.stateModel);
            $element.after(templateElem);
            $element.remove();
            var subLink = $compile(templateElem);
            return {
                pre: function(scope, element, attrs) {
                    subLink(scope);
                },
                post: function(scope, element, attrs) {
                }
            }
        }
    };

});

可以在此处找到此操作的示例:http://jsfiddle.net/u5uz2po7/2/

该示例使用隔离范围,以便将“状态”应用于该范围不会影响现有范围。这也是“$parent”的原因。在 ng 模型中。

关于angularjs - 在渲染模板之前编译指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27029156/

相关文章:

javascript - AngularJS在指令模板中执行 Controller 函数

angularjs - 显示/隐藏div取决于AngularJS中的下拉列表选择

javascript - angularjs指令使用 Controller 作为vm而不是作用域

javascript - 事件监听器的指令优先级

javascript - AngularJS : invoking optional nested directive on template sub-element

javascript - 无法从自定义服务返回对 AngularJS 范围的引用

javascript - 如果条件为真,则更改悬停属性

angularjs - 如何编译 $http 请求返回的数据?

javascript - 使用 ng-submit + ng-model 添加 JSON 对象

angularjs - 获取 $rootScope :inprog error, 但它需要scope.$apply 才能工作