设置要显示的文本格式的指令

Directive to format text to be displayed

本文关键字:格式 指令 文本 设置 显示      更新时间:2023-09-26

我正在玩AngularJS directive。我想格式化要显示的数据。这就是我正在做的:

.HTML:

<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-model="data" type="text" test />
  <input type="button" ng-click="change()" value="Change"> {{data}}
  <br>Hello <span ng-bind="data" test></span>
</div>

.JS:

angular.module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.data = 'yellow';
    $scope.change = function() {
      $scope.data = 'black';
    };
  })
  .directive('test', function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ngModel) {
        ngModel.$formatters.push(function(value) {
          //formats the value for display when ng-model is changed
          return 'brown';
        });
        ngModel.$parsers.push(function(value) {
          //formats the value for ng-model when input value is changed
          return 'green';
        });
      }
    };
  });

我能够格式化模型的数据并将其显示为input文本。但是我无法格式化绑定到模型的span的数据。 span按原样显示模型。我不知道为什么跨度显示模型的值。我还想向范围显示格式化的值。这是jsFiddle。

您只能将 ng-model 用于input。如果要在没有输入的情况下更改div,span,label或任何其他元素中的文本,则可以使用分隔符。 {}

在 $scope 中创建变量时,可以在 html 中显示它。

<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-model="data" type="text" test />
  <input type="button" ng-click="change()" value="Change"> {{data}}
  <br>Hello <span test>{data}</span>
</div>

小提琴

我认为它工作得很好,唯一的问题是你在这里没有采取正确的例子。

首先请阅读以下内容:

  1. 格式化程序更改模型值在视图中的显示方式。
  2. 解析器更改视图值在模型中的保存方式。

现在替换下面的代码

ngModel.$formatters.push(function(value) {
          //formats the value for display when ng-model is changed
          return 'brown';
        });
        ngModel.$parsers.push(function(value) {
          //formats the value for ng-model when input value is changed
          return 'green';
        });

ngModel.$formatters.push(function(value) {
          //formats the value for display when ng-model is changed
          return value.toLowerCase();
        });
        ngModel.$parsers.push(function(value) {
          //formats the value for ng-model when input value is changed
          return value.toUpperCase();
        });

我希望这有帮助!!