简体   繁体   中英

AngularJS custom directive using event listener

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

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!

Try this:

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 .

Old question, but to address the actual issue:

I believe htmlTxtBox.addEventListener('focus', setFocus(), false); should have just setFocus instead to pass the reference to the function rather than call it within the addEventListener call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM