使用带有非输入元素的ngModel。$ formatter

时间:2016-03-04 22:10:57

标签: angularjs

我很高兴使用$parsers$formatters操纵视图来转换表单中的数据。然而,当我开始将相同的行为应用于其他元素时,我发现它不起作用,如下所示:



angular.module("app", [])
  .controller("foo", function ($scope) {
    $scope.n = 1;
  })
  .directive("displayHalf", function () {
    return {
      require: 'ngModel',
      link: function (scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function (value) {
          return value*2;
        });

        ngModel.$formatters.push(function (value) {
          return value/2;
        });
      }
    };
  });

<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body ng-app="app">
  <div ng-controller="foo">
    <div>
      Input: <input type="number" display-half ng-model="n">
    </div>
    <div>
      Span: <span display-half ng-model="n">{{n}}</span>
    </div>
    <div>
      Button: <button display-half ng-model="n">{{n}}</button>
    </div>
    <div>
      Div: <div display-half ng-model"n">{{n}}</div>
    </div>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

我想我希望在显示数据时应用$formatter,即使它无法编辑。我弄错了吗?没有在任何地方写{{n / 2}}的任何方法来实现这个目的吗?

0 个答案:

没有答案