2017-08-25 61 views
0

有一些代碼追趕的keyCode == 13 Angularjs

app.directive('currencyInput', function ($filter, myFactory) { 
return { 
    require: '?ngModel', 
    link: function (scope, elem, attrs, ctrl) { 
     ctrl.$formatters.unshift(function() { 
      return $filter('number')(ctrl.$modelValue); 

     }); 

     ctrl.$parsers.unshift(function (viewValue) { 
      let plainNumber = viewValue.replace(/[\,\.]/g, ''), 
       b = $filter('number')(plainNumber); 

      elem.val(b); 
      //here I need to add listener if keyCode==13 
      return plainNumber; 
     }); 
    } 
}; 
}); 

所以,我需要趕上如果的keyCode == 13。我怎麼能在我添加評論的地方做到這一點?我需要採取一些措施:

elem.bind('keydown keypress', ($event) => { 
    if ($event.which === 13) { 
    let val=$element.val(); 
    if(attrs['param']=="amount") myFactory.process[attrs['param']]=val*24; 
    else myFactory.process[attrs['param']]=$element.val(); 
    let i=0; 
    for(let key in myFactory.process){ 
     if(myFactory.process[key]===""){ 
       scope.dashboard.currParam=i;//this doesn't works until user make one more action. 
       break; 
     } 
     i++; 
    } 
    } 
}) 

但並非所有動作都「立即行動」,用戶點擊進入。 myFactory.process看起來像

process: { 
     cost:"", 
     amount:"", 
     wrapping:"", 
     risk:"", 
     limit:"", 
     franchise:"" 
    }, 

此字符串scope.dashboard.currParam=i;必須更新視圖(DOM)。但是直到我點擊輸入後纔會更新。

+0

我不認爲你可以做到這一點不久 –

回答

0

問題成爲關注焦點。所以,你需要做類似:

elem.bind('keydown keypress', ($event) => { 
if ($event.which === 13) { 
let val=$element.val(); 
if(attrs['param']=="amount") myFactory.process[attrs['param']]=val*24; 
else myFactory.process[attrs['param']]=$element.val(); 
let i=0; 
for(let key in myFactory.process){ 
    if(myFactory.process[key]===""){ 
      scope.dashboard.currParam=i; 
      let target = $event.target; 
      target.blur();//this helps 
      break; 
    } 
    i++; 
} 
} 
}) 
0

您可以使用此代碼做到這一點:

elem.bind('keydown keypress', ($event) => { 
    if ($event.which === 13) { 
    scope.$apply(() => scope.$eval(attrs.enter, { $event }); 
    // enter key pressed here 
    } 
}); 
+0

的問題是,用戶點擊「Enter」之後我需要做的功能,但它不會做直到用戶再做一個動作(點擊,按鍵等)。我該如何解決這個問題? – RoGGeR

+0

更新的問題,希望你的問題是什麼;( – RoGGeR

+0

那麼,什麼是myFactory.process,在你的代碼中?是否是其他鍵的列表? – rrd