使用angularjs

时间:2016-12-21 20:15:00

标签: angularjs focus directive

我有一个模态用于显示购物车中的订单项。在此购物车模式中,我在不同的行上显示每个带有数量输入框的项目。每次将新项目添加到购物车时,模态 打开时最新添加的项目位于顶部。我想将焦点显示在最近添加的项目的数量输入框中。

我找到了一个很好的例子,说明如何让angularjs通过创建自定义指令并将'focus-me'指令添加到我的输入框来将焦点设置在特定项目上。我遇到的问题是重点是留下来 将第一个项目添加到购物车。这是我的HTML:

<div id="shoppingCart" ng-show="cartItems.length > 0" ng-repeat="scItem in cartItems track by $index ">
<div id="shoppingCartItems">
    <fieldset >
        <div class="shoppingCartItem">
            <div id="scCol1">
                <div class="lineItemDetail">
                    <strong>Item #{{ scItem.lineId }}</strong>
                </div>
                <img src="{{ scItem.imageUrl }}">
            </div>
            <div id="scCol2">
                <div class="lineItemDetail">
                    <strong>Qty:</strong>
                    <span>
                        <!-- Put the focus on the qty box if the item was just added to cart -->
                        <input type="text" 
                        name="qty_{{$index}}" 
                        maxlength="7" 
                        size="4" 
                        focus-me="true" 
                        ng-keypress="shoppingCartKeyCheck($event)" 
                        ng-model="scItem.qty" 
                        ng-blur="validateQty(scItem.lineId)"/>
                    </span>
                    <span id="invalidQuantity" ng-show="scItem.validationMessage" ng-bind-html="$sce.trustAsHtml(scItem.validationMessage)"></span>
                </div>
                <div class="lineItemLink">
                    <a href="" ng-click="removeSelectedProduct(scItem.lineId)" class="removeShoppingCartItemLink">Remove From Cart</a>
                </div>
            </div>
            <br/>                       
        </div>
    </fieldset>
</div>
</div>

这是我的自定义指令:

app.directive('focusMe', function($timeout) {
return {
    scope: { trigger: '@focusMe' },
    link: function(scope, element) {
        scope.$watch('trigger', function(value) {

            if(value === "true") {
                console.log("its true");

                $timeout(function() {
                    element[0].focus();
                });
            }
        });
    }
};
});

我怀疑这与以下事实有关:在添加第一个购物车项目时设置焦点,并且在添加后续项目时不会删除/重置焦点。关于我在这里需要做什么,我有点困惑。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

这个应该有帮助

focus-me="{{$index == 0}}"