Javascript 使用事件侦听器的AngularJS自定义指令

Javascript 使用事件侦听器的AngularJS自定义指令,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我试图创建一个自定义指令,其中包含一个文本框,当用户单击按钮时,该文本框将显示、展开并聚焦。当用户从展开的文本框中单击时,它应该最小化、消失,然后显示原始按钮。 以下是我目前掌握的情况: 以下是我遇到问题的部分: if (htmlTxtBox.addEventListener !== undefined) { console.log("first"); htmlTxtBox.addEventListener('focus', setFocus(), false); //th

我试图创建一个自定义指令,其中包含一个文本框,当用户单击按钮时,该文本框将显示、展开并聚焦。当用户从展开的文本框中单击时,它应该最小化、消失,然后显示原始按钮。 以下是我目前掌握的情况:

以下是我遇到问题的部分:

  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();
}
以及与事件侦听器一起运行的相应函数:

function setFocus()  {
        scope.$apply('showInput = true');
        console.log("setFocus: " + scope.showInput);    
    }
function setNoFocus(){
  scope.$apply('showInput = false');
  console.log("setNoFocus: " + scope.showInput);
}
我的问题是setFocus和setNoFocus函数无论如何都会运行。如何构造这些函数,使其仅在文本框聚焦或模糊时运行? 谢谢你的帮助。谢谢

试试这个:

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'});
        });
    };    
...

jshiddle.

旧问题,但为了解决实际问题:


我相信
htmlTxtBox.addEventListener('focus',setFocus(),false)
应该只使用
setFocus
将引用传递给函数,而不是在addEventListener调用中调用它

那是票!现在我正在尝试添加一个明文图标…我尝试了以下操作,但没有成功:@MichaelAny使用
$.bind
而不是
$的具体原因。
上?@pilau Angular的jqLite在早期版本中只有
bind
。这在版本1.2RCx中发生了变化,因为他们将
bind
替换为
on
。这很有趣,因为在jQuery中,
$.bind
允许侦听由
$.event.trigger()
触发的自定义(非DOM)事件,而
$.on
则不允许。但如果您的Angular架构正确,这一点都不重要。为什么在事件处理程序函数中使用scope.$apply()?