在 AngularJS 的 table 添加的行上显示 3 秒的弹出框

Show an popover for 3 second on added row in table in AngularJS

我想做什么:我有 table 由 ngRepeat 绑定到 angularJs 中控制器的集合。当我在控制器中通过 collection.unshift(newItem) 添加项目时,我希望弹出窗口显示在新添加行的第一列上。

我是如何实现的:

 <table> 
      <tr ng-repeat="item in items">
         <td>
           <a popover-on-show>{{item.Name}}</a>
         </td>
       </tr>
 </table>

和指令:

.directive('popoverOnShow', function ($timeout) {
        return {
            restrict:"A",
            link: function (scope, element, attrs) {
                element.popover({
                    trigger: "manual",
                    html: true,
                    content: "This is a new added item",
                    placement: "right"
                }).popover('show');
                $timeout(function () { element.popover('hide'); }, 1000);
            }
        }
    });

问题是,当我在初始化控制器中执行操作时: $scope.items = resource.query(); 弹出窗口在所有项目上显示一秒钟,我如何告诉指令在初始加载时不显示弹出窗口?

如果您在 link 函数期间调用 show,它将显示为 linked 指令。我建议使用手表在运行时显示弹出窗口。

类似于:

scope.$watch('items', function(newValue, oldValue) {
    // Do nothing during initial run
    if (newValue != oldValue){
        if (<isLastElement>){
            <showPopover>
        }
    }
};

我解决了,但对我来说似乎是完全错误的,所以我希望有更好的解决方案。我所做的是在控制器中设置一个 initializing 属性 并在指令中检查它。

来自控制器的代码段:

$scope.refresh = function () {
    $scope.initializing = true;
    $scope.projects = null;
    someResource.query().$promise.then(function (result) {
        $scope.projects = result;
        $timeout(function () { $scope.initializing = false; });
    });
}

指令:

  .directive('popoverOnShow', function ($timeout) {
        return {
            restrict:"A",
            link: function (scope, element, attrs) {
                if (!scope.$parent.$parent.initializing && scope.$first) {
                    element.popover({
                        trigger: "manual",
                        html: true,
                        content: "<div>Just added this item</div>",
                        placement: "right"
                    });
                    $timeout(function () { element.popover('show'); });
                    $timeout(function () { element.popover('hide'); }, 3000);
                }
            }
        }
    });