0

在我的示例中,我想在用户关注文本字段时更新模型。简而言之,将“px”字符串附加到现有值。

HTML:

<div ng-app>
  <div ng-controller="PixelCtrl">
  <div>
  {{pixel}}
  </div>
    <input type="text" ng-focus="updatePX($event)" ng-model="pixel" />
  </div>
</div>

JS:

function PixelCtrl($scope) {
  $scope.pixel = "120";

  $scope.updatePX = function(e){
  debugger;
   alert(e.target.value);
    e.target.value = e.target.value + "px";
    $scope.$apply();
  }
}

大家可以看到我也用过$scope.$apply。很可能我做错了什么。

JSFIDDLE:https ://jsfiddle.net/ashwyn/U3pVM/27621/

4

3 回答 3

2

您无需手动添加“px”文本。只需默认添加即可

function PixelCtrl($scope) {
  $scope.pixel = "120";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="PixelCtrl">
    <div ng-show="pixel">
      {{pixel}} px
    </div>
    <input type="text" ng-model="pixel" />
  </div>
</div>

于 2016-10-06T13:59:33.890 回答
0

正如@Alexandru Mihai 所说,升级角度版本。

请参阅jsfiddle上的示例。

angular.module("testApp", [])
  .controller("PixelCtrl", function($scope) {
    $scope.pixel = "120";

    $scope.updatePX = function(e) {
      if ($scope.pixel && $scope.pixel.indexOf("px") === -1)
        $scope.pixel += "px";
    }
  })
  .directive("myPixel", function() {
    return {
      require: "ngModel",
      link: function(scope, element, attr, ngModel) {
        element.on("focus", function() {
          var val = ngModel.$viewValue;
          if (val && val.indexOf("px") === -1) {
            ngModel.$setViewValue(ngModel.$viewValue + "px");
            element.val(ngModel.$viewValue);
          }
        })
      }
    }
  })
  .directive("myPixelBetter", function() {
    return {
      scope: {
        value: "=myPixelBetter"
      },
      link: function(scope, element) {
        element.on("focus", function() {
          if (scope.value && scope.value.indexOf("px") === -1) {
            scope.value += "px";
            scope.$apply();
          }
        })
      }
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="testApp">
  <div ng-controller="PixelCtrl">
    <div>
      {{pixel}}
    </div>
    <div>

      With ng-focus
      <input type="text" ng-focus="updatePX()" ng-model="pixel" />
    </div>
    <div>
      With custom directive
      <input type="text" my-pixel ng-model="pixel" />
    </div>
    <div>
      With custom directive. Better solution
      <input type="text" my-pixel-better="pixel" ng-model="pixel" />
    </div>
  </div>
</div>

于 2016-10-06T15:20:59.930 回答
0

您必须包含 1.2.1 角度版本。这是您的解决方案: jsfiddle

<div ng-app>
  <div ng-controller="PixelCtrl">
   <div>
      {{pixel}}
   </div>
   <input type="text" ng-focus="updatePX($event)" ng-model="pixel" />
  </div>
</div>



function PixelCtrl($scope) {
   $scope.pixel = "120";
   $scope.updatePX = function(e){
     e.target.value = e.target.value + "px";
     $scope.pixel=e.target.value;
   }
}
于 2016-10-06T14:21:06.410 回答