我正在使用AngularJS 1.6.x,并使用ng-repeat建立一个表,如下所示。但是,现在我需要根据一些动态布尔条件(即isDynamicVisible)显示一个新列:

<table>
    <thead>
    <tr>
        <th id="name">Name</th>
        <th id="mean">Mean</th>
        <th ng-if="isDynamicVisible">Dynamic</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="data in displayedPathStatistics" ng-class="{selected: (histogramData.selected === data.name)}"
        ng-click="selectPathOutputRow(data.name)">
        <td>{{data.displayName}}</td>
        <td>{{data.Mean}}</td>
        <td ng-if="isDynamicVisible">{{dynamicVal}}</td>
    </tr>
    </tbody>
</table>


在控制器端:

constructor(private $window: IWindowService, private $rootScope: IRootScopeService, private $scope:IReportCtrlScope, private $location:ng.ILocationService, private remoteServices: RemoteServices) {
    $scope.isDynamicVisible = false;

    // ...
    objects.selectAll(".dot")
    .data(data)
    .enter().append("circle")
    .classed("dot", true)
    .attr("r", function (d) {
            return 6 * Math.sqrt(2.0 / Math.PI);
    })
    .attr("transform", transform)
    .style("fill", colorVal)
    .on("mouseover", function(d) {
        $scope.isDynamicVisible = true;
        return tip.show(d);
    })
    .on("mouseout", function(d) {
        $scope.isDynamicVisible = false;
        return tip.hide(d);
    });


问题在于,条件在开始和构造表时仅被评估一次,以后无论isDynamicVisible范围变量如何变化,它都将保持最初的状态。我也尝试使用ng-show失败。

更新:isDynamicVisible从控制器更改,特别是当用户将鼠标悬停在D3 JS散点图的数据点上时。

最佳答案

如果您的监听器是从非角度上下文触发的(即从D3触发),则必须将$scope属性的修改包装在$scope.$apply调用下:

.on("mouseover", function(d) {
    $scope.$apply(function () {
        $scope.isDynamicVisible = true;
    }
    return tip.show(d);
})
.on("mouseout", function(d) {
    $scope.$apply(function () {
        $scope.isDynamicVisible = false;
    }
    return tip.hide(d);
})


因此,Angular摘要循环将开始,您的视图将更新。

09-25 19:21