我正在为 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/