gpt4 book ai didi

javascript - Angular $compile on scope with ng-repeat 不起作用

转载 作者:行者123 更新时间:2023-11-30 12:55:46 24 4
gpt4 key购买 nike

我有一个使用 $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")取消订阅事件以避免闪烁。

DEMO

关于javascript - Angular $compile on scope with ng-repeat 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com