gpt4 book ai didi

angularjs - 如何在指令中插入 $compile 的 HTML 代码而不出现 $digest 递归错误?

转载 作者:行者123 更新时间:2023-12-02 23:50:52 25 4
gpt4 key购买 nike

我有一个指令,取决于 ng-repeat项目数据(来自数据库),使用 switch case 构建自定义 HTML:

app.directive('steps', function($compile){
return {
'restrict': 'A',
'template': '<h3>{{step.name}}</h3><ul ng-repeat="opt in step.opts"><div ng-bind-html-unsafe="extra(opt)"></div></ul>',
'link': function($scope, $element){
$scope.extra = function(opt){
switch ($scope.step.id){
case 1:
return "<div>Some extra information<select>...</select></div>"
case 2:
return "<div><input type='checkbox' ng-model='accept'> Accept terms</div>"
case 3:
return "<div>{{step.title}}<select multiple>...</select></div>"
}
}
}
}
});

上面的代码可以工作,但是可绑定(bind) {{step.title}}函数内部不起作用。我试过$compile(html)($scope)但它给了我一个Error: 10 $digest() iterations reached. Aborting! 。我该如何处理这个问题?

最佳答案

答案是为每个选项创建一个“sub”指令,这样您就可以按值绑定(bind)它们,而不是使用参数调用函数。你离开了程序化 Javascript,但程序化 Javascript 并没有离开你

app.directive('opt', function($compile){
return {
'restrict': 'A',
'template': '<div>{{extra}}</div>',
'link': function($scope, $element){
switch ($scope.step.id){
case 1:
extra = "<div>Some extra information<select>...</select></div>";break;
case 2:
extra = "<div><input type='checkbox' ng-model='accept'> Accept terms</div>";break;
case 3:
extra = "<div>{{step.title}}<select multiple>...</select></div>";break;
}

$scope.extra = $compile(extra)($scope);
}
}
});

app.directive('steps', function(){
return {
'restrict': 'A',
'template': '<h3>{{step.name}}</h3><ul><li ng-repeat="opt in step.opts" opt></li></ul>',
'link': function($scope, $element){
}
}
});

关于angularjs - 如何在指令中插入 $compile 的 HTML 代码而不出现 $digest 递归错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16269184/

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