为什么不用ng-keypress改变ng-model值

时间:2014-03-17 22:34:23

标签: javascript html angularjs angularjs-directive

请查看我的jsFiddle

鼠标悬停在div .box.red ||上.box.blue将允许对其进行关注,并将值更改为ng-model以进行更改

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

此更改发生在ng-keyup ng-keydown事件期间。

keyup会将+1更改为该值; keydown会将值更改为-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 个答案:

答案 0 :(得分:2)

在你的小提琴上你使用的AngularJS 1.0.1还没有ng-keypress指令。 如果您无法更改正在使用的角度版本,则可以编写自己的按键指令:

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

和标记如:

<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>

我更新了你的小提琴,告诉你这个。 http://jsfiddle.net/HB7LU/2627/