如何在 angular 指令(即 ng-init)r 的字符串插值中使用对象?

How I can use object in string interpolation in angular directive (i.e ng-init)r?

我有一个函数可以创建 angular 元素并通过 jquery 附加到容器。我想使用 ng-init。按照我的代码。

 _createItem = function (chart) {

        let item = angular.element(
          `<div class="item col-xs-4 col-sm-4 col-md-4 col-lg-4" ng-init="chart = ${chart}">


        </div>`);

        $compile(item)($scope);
        $(".grid").append(item);

      }

使用上面的代码应用会产生语法错误。

您的代码包含两个问题。首先是如何进行字符串插值。由于 chart 是一个对象,字符串插值机制将在执行其工作时调用其 toString 方法,因此您将得到 <div class="item col-xs-4 col-sm-4 col-md-4 col-lg-4" ng-init="chart = [object Object]"></div> (带换行符)而不是您期望的。此外,在这种情况下 ng-init 内容不是有效的 AngularJS 表达式。下一个问题是如何将对象传递到 AngularJS 模板中。您编译的模板绑定到特定范围,因此它只能访问范围级别的对象。注意您在答案下的评论中提到的问题,我建议为每个图表创建单独的范围。因此,您必须按如下方式更改代码:

_createItems = function () {
        const itemsData = $scope.$ctrl.chartList;
        for (let i = 0; i < itemsData.length; i++) {
             let chart = itemsData[i];
             _createItem(chart);
        }
}

_createItem = function (chart) {
        let newScope = $scope.$new(true); // if you need to inherit $scope properties, pass false here
        newScope.chart = chart;

        let item = angular.element(
          `<div class="item col-xs-4 col-sm-4 col-md-4 col-lg-4" ng-init="chart = chart">


        </div>`);

        $compile(item)(newScope);
        $(".grid").append(item);

      }

最后,我认为 ng-init 在这个特定示例中没有意义,因为 chart 已经在 newScope 中定义。