如何在AngularJS环境下实现iziToast中的ng-repeat数组循环渲染
AngularJS 中iziToast内实现ng-repeat循环渲染的方案
核心原理:iziToast默认仅支持传入静态HTML字符串,无法直接识别AngularJS内置指令(如ng-repeat),需要借助AngularJS的$compile服务手动编译模板,关联当前作用域后再插入iziToast容器。
具体实现步骤
- 第一步:在对应的控制器/自定义指令中注入依赖
$compile和$scope,如果使用controller as语法,需要将当前控制器实例挂载到$scope上,示例:
angular.module('yourApp').controller('YourController', ['$scope', '$compile', function($scope, $compile) { const self = this; $scope.self = self; // 确保模板内可以访问到控制器实例 // 你的原有数据定义 self.quantitativeEvaluationQuestions = [/* 你的数组数据 */]; self.completeInfo = {/* 你的业务数据 */}; }]);
- 第二步:定义带
ng-repeat逻辑的渲染模板,和你原有表格逻辑保持一致即可:
const toastContentTemplate = ` <table class="your-custom-table-class"> <tr ng-repeat="item in self.quantitativeEvaluationQuestions"> <th>{{ item.key }}</th> <td ng-bind="self.completeInfo[item.value] | quantitativeEvaluationOptionsFilterVc"></td> </tr> </table> `;
- 第三步:编译模板并调用iziToast渲染:
// 编译模板,关联当前作用域生成可执行的DOM const compiledContent = $compile(angular.element(toastContentTemplate))($scope); // 等待作用域 digest 完成,确保ng-repeat逻辑渲染完毕后再挂载到iziToast $scope.$applyAsync(() => { iziToast.show({ theme: 'light', title: '定量评估结果', // 推荐用onOpen钩子插入编译好的DOM,避免HTML字符串转义问题 onOpen: function (instance, toast) { // 找到iziToast的内容容器,插入编译完成的DOM angular.element(toast).find('.iziToast-message').append(compiledContent); } }); });
内容的提问来源于stack exchange,提问作者Mehrdad Kiani Anbohi
相关产品推荐
相关产品推荐

