why wont ng-keypress change ng-model values

2019-08-14 16:44发布

问题:

Please check out my jsFiddle

Mousing over divs .box.red || .box.blue will allow it to be focused and values to change of ng-model to be changed

scope.box = {'blue': 0, 'red': 0};

This change happens during a ng-keyup ng-keydown event.

keyup will change +1 to the value; keydown will change value by -1.

html

    <div  ng-controller="MyCtrl">
    <div class="bounding">
        <h2><i>mouseover</i> box then <i>keypress</i> <span>up</span> or <span>down</span> arrows indivually edit values of input model </h2>
        <div  ng-keyup="box.red = box.red + 1"  class="box red"></div>
        <div  ng-keypress="box.blue = box.blue + 1" class="box blue"></div>
        <div style="margin-top: 10px;">

          <label for="red">Red</label>
          <input type="text" ng-model="box.red" />

          <label for="blue">Blue</label>
          <input type="text"  ng-model="box.blue" />
        </div>
    </div>

</div>

js

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.box = {'blue': 0, 'red': 0};
}

CSS

.box {
    width:50px;
    height: 50px;
    display:inline-block;
    float: left;
    margin-right: 20px;
    cursor: all-scroll;
}
.red {
    background: red;

}
.red:hover {
    box-shadow: 0px 0px 15px red;
}
.blue {
    background: blue;
}
.blue:hover {
    box-shadow: 0px 0px 15px blue;
}
.bounding {
     width: 80%;
    margin:20% auto;

}
h2 {
    text-transform: uppercase;
    font-size: 14px;
    border-bottom: 1px solid #ccc;
    font-weight: bold;
    color: #444;
    font-family: arial;
}
h2 span {
    color: orange;
}
h2 i {
    color: green;
}

回答1:

On your fiddle you are using AngularJS 1.0.1 which didn't have the ng-keypress directive yet. If you cannot change the angular version you are using you can write your own keypress directive:

myApp.directive('myKeypress', function() {
  return function(scope, elm, attrs) {
    elm.bind("keypress", function() {
      scope.$apply(attrs.onKeypress);
    });
  };
});

and the markup like:

<div tabindex='1' my-keypress on-keypress="box.red = box.red + 1"  class="box red"></div>
<div tabindex='1' my-keypress on-keypress=" box.blue = box.blue + 1 " class="box blue"></div>

I updated your fiddle to show you this. http://jsfiddle.net/HB7LU/2627/