我有一个使用 $compile
的指令服务生成模板。它不会使用 ng-options
生成选择选项或 ng-repeat
,即使我显然有 users
在我的范围内设置的数组。为什么这不起作用?这只是给我一个空白 <select>
没有选项的字段。
angular.module("myApp").directive("selectForm", [
'$compile',
function($compile) {
return {
restrict: 'C',
scope: true,
link: function(scope, element, attrs) {
scope.users = [
{ id: 1, name: "User 1" },
{ id: 2, name: "User 2" }
];
element.on('click', function(e) {
var selectHtml = $compile('\
<select\
class="col-lg-2 form-control"\
ng-options="user.id as user.name for user in users">\
</select>\
')(scope);
$(element).html(selectHtml);
});
}
}
}
]);
最佳答案
您的代码中需要更改一些内容才能使其正常工作:
-
<select>
仅当您还提供ng-model
时才有效 - 将您的代码包装在
scope.$apply
中. - 调用
element.off("click")
取消订阅事件以避免闪烁。
关于javascript - Angular $compile on scope with ng-repeat 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204883/