2014-01-13 60 views
0

工作在文本輸入使用一個指令focus-me="inTextModeInput"角NG-模糊不與納克隱藏

app.directive('focusMe', function($timeout) { 
    /*focuses on input 
    <input type="text" focus-me="focusInput"> 
    */ 
     return { 
      scope: { trigger: '=focusMe' }, 
      link: function(scope, element) { 
       scope.$watch('trigger', function(value) { 
        if(value === true) { 
         $timeout(function() { 
          element[0].focus(); 
          scope.trigger = false; 
         }); 
        } 
       }); 
      } 
     }; 
    }); 

實際上具有2個輸入,既使用focus-me 當我編程設爲焦點上的輸入值的ng-blur其他不叫。

注意:我也在ng-repeat中使用它。

回答

2

隔離範圍

模糊叫,但你沒有看到因爲你已經創建了一個孤立的範圍指令。 ng-blur$parent範圍內執行。當指令執行可重複使用的模板時,您應該只使用隔離範圍。

雙向上觸發

線結合「scope.trigger =假」也設置不同的布爾值,因爲它是在不同的範圍。如果你想從一個指令中給一個變量賦值,你應該總是把這個值包含在另一個對象中:var focus = { me: true }並將其設置爲trigger=focus.me

更好的解決方案

但我不會設置triggerfalse可言。 AngularJS是一個基於MVC/MVVM的框架,它具有用戶界面的模型狀態。這個狀態應該是idempotent;這意味着如果您存儲當前狀態,請重新加載頁面並恢復用戶界面應與以前完全相同的狀態。

所以你可能需要的是一個指令,

  • 沒有孤立範圍(允許所有其他指令的工作:NG-模糊,NG-焦點,...)
  • 跟蹤一個布爾值,指示焦點狀態
  • 設置這個布爾假當元素已失去焦點

它可能更容易在行動中看到這一點:working plunker

也許this (other) plunker會給你更多關於範圍和指令的見解。

代碼

myApp.directive('myFocus', function($parse, $timeout) { 

    return { 
    restrict: 'A', 
    link: function myFocusLink($scope, $element, $attrs, ctrls) { 

     var e = $element[0]; 

     // Grab a parser from the provided expression so we can 
     // read and assign a value to it. 

     var getModel = $parse($attrs.myFocus); 
     var setModel = getModel.assign; 

     // Watch the parser -- and focus if true or blur otherwise. 

     $scope.$watch(getModel, function(value) { 
      if(value) { 
      e.focus(); 
      } else { 
      e.blur(); 
      } 
     }); 

     function onBlur() { 
      $timeout(function() { 
      setModel($scope, false); 
      }); 
     } 

     function onFocus() { 
      $timeout(function() { 
      setModel($scope, true); 
      }); 
     } 

     $element.on('focus', onFocus); 
     $element.on('blur', onBlur); 

     // Cleanup event registration if the scope is destroyed 

     $scope.$on('$destroy', function() { 
      $element.off('focus', onFocus); 
      $element.off('blur', onBlur); 
     }); 
    } 
    }; 
});