AngularJS使用事件侦听器定制指令

AngularJS使用事件侦听器定制指令

本文介绍了AngularJS使用事件侦听器定制指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含显示,扩大,当用户点击一个按钮集中在一个文本框自定义指令。而当用户从扩展的文本框中点击了它应尽量减少,消失,然后显示原始按钮。
这是我到目前为止有:

I am trying to create a custom directive that contains a text box that is shown, expanded and focused when a user clicks a button. And when the user clicks away from the expanded text box it should minimize, disappear and then show the original button.Here's what I have so far:http://jsfiddle.net/Z6RzD/152/

下面是我有问题的部分:

Here is the section that I am having problems with:

  if (htmlTxtBox.addEventListener !== undefined) {
  console.log("first");

  htmlTxtBox.addEventListener('focus', setFocus(), false);
  //this function is automatically called even when textBox is in focus
  //htmlTxtBox.addEventListener('blur', setNoFocus(), false);
  console.log("ifHasFocus: " + scope.showInput);
} else if (htmlTxtBox.attachEvent != undefined) {
  console.log("second");
  htmlTxtBox.attachEvent('onfocus', setFocus());
  htmlTxtBox.attachEvent('onblur', setNoFocus());
} else {
  console.log("third");
  htmlTxtBox.onmouseover = setFocus();
  htmlTxtBox.onmouseout = setNoFocus();
}

和与该事件侦听器运行相应的功能:

And the corresponding functions that run with the event listener:

function setFocus()  {
        scope.$apply('showInput = true');
        console.log("setFocus: " + scope.showInput);
    }
function setNoFocus(){
  scope.$apply('showInput = false');
  console.log("setNoFocus: " + scope.showInput);
}

我的问题是,和的setFocus功能setNoFocus跑不管。我该如何组织这些功能,他们只运行在文本框的重点或模糊?
我AP preciate任何帮助。谢谢!

My problem is that the setFocus and setNoFocus functions run no matter what. How can I structure these functions to where they run only when the textbox is focused or blurred?I appreciate any help. Thanks!

推荐答案

试试这个:

myApp.directive('replybox', function($timeout) {
    var linkFn = function(scope, element, attrs) {
        scope.showInput = false;

        var button = element.find('button');
        var input = element.find('input');

        button.bind("click", function() {
            scope.showInput = true;
            scope.$apply();

            input[0].focus();
            input.css({"width":"300px","transition":"1s"});
        });

        input.bind('blur', function() {
            scope.showInput = false;
            $timeout(function() { scope.$apply(); }, 1000);

            input.css({'width':'0px', 'transition':'1s'});
        });
    };
...

这里。

这篇关于AngularJS使用事件侦听器定制指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:50