angularjs没有更新模型值

时间:2016-10-06 13:55:44

标签: angularjs angularjs-scope angularjs-model

在我的示例中,我想在用户聚焦文本字段时更新模型。简而言之,将'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/

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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;
   }
}

答案 2 :(得分: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>