2013-08-26 53 views
2

我想创建一个自定义指令,其中包含一个文本框,当用户单击按钮时显示,展开和聚焦。而当用户点击远离扩展文本框时,它应该最小化,消失并显示原始按钮。 这是我到目前为止有: http://jsfiddle.net/Z6RzD/152/AngularJS自定义指令使用事件侦听器

这里是我有问题的部分:

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函数无论如何运行。如何才能将这些功能构建到只有当文本框聚焦或模糊时才运行的位置? 我感谢任何帮助。谢谢!

回答

5

试试这个:

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

的jsfiddle here

+0

这就是机票!现在我试图添加一个明确的文本图标...我尝试了以下,但无济于事:http://jsfiddle.net/Z6RzD/158/ @Michael – sh3nan1gans

+1

任何使用'$ .bind'的具体原因,而不是'$ .on'? – pilau

+1

@pilau Angular的jqLit​​e在早期版本中只有'bind'。这在1.2RCx版本中已经改变了,因为它们已经用'on'代替了'bind'。 –

相关问题