Angular:一旦您聚焦输入(搜索框),如何显示按钮?

时间:2015-01-29 20:50:55

标签: angularjs

我正在移动应用程序中工作,我有一个搜索框,右侧有一个清除按钮,显然是在您决定时清理搜索框。

我有一个指令,我不知道为什么不工作:

angular.module('myApp', [])
  .directive('FocusOnVisibility', function($timeout) {
    return function (scope, element, attrs) {
              console.log(scope.showInput)
        //Watch the showInput model
        scope.$watch('showInput', function () {
            //If the model changes to true, focus on the element
            if (scope.showInput === undefined) {
                //Assumes that the element has the focus method
                //If not, then you can have your own logic to focus here
                element.focus();
            }
        });
    };
});

这是一个搜索框,其中包含我希望在输入焦点后显示的按钮

    <label>
       <!--once focus this input, the button below must be shown-->
      <input type="search"
             ng-click="showInput=true
             ng-model="query">
    </label>

    <button class="button-clear" FocusOnVisibility
            ng-show="showInput"
            ng-click="query = null">
      CANCEL
    </button>

更新

我已经通过将ng-click="showInput=true"添加到输入字段来修复它,但现在我遇到的问题是,一旦离开输入,该按钮就不会消失。

1 个答案:

答案 0 :(得分:2)

Angular具有开箱即用的功能:

<input ng-focus="showButton = true" ng-blur="showButton = false">
<button ng-show="showButton">wat</button>

Plunker