Angular Directive:未调用ngModelController自定义解析器

时间:2015-09-08 16:03:26

标签: angularjs angularjs-directive angular-ngmodel angularjs-ng-model

我知道我可以在我的指令中使用格式化程序和解析器来转换我的数据:

  //format text going to user (model to view)
  ngModel.$formatters.push(function(value) {
    return value.toUpperCase();
  });

  //format text from the user (view to model)
  ngModel.$parsers.push(function(value) {
    return value.toLowerCase();
  });

此处的完整示例http://plnkr.co/edit/i59xSdVPMxRkgERhj8RE?p=preview

但是当我在我的指令中使用模板时,我无法使用它。我的自定义解析器未被调用:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = { name: ''};
});
app.directive('changecase', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    scope: { model: '=ngModel' },
    template: '<input type="text" ng-model="model"> {{ model }}',
    link: function (scope, element, attrs, ctrl) {

      //format text going to user (model to view)
      ctrl.$formatters.push(function(value) {
        return value.toUpperCase();
      });

      //format text from the user (view to model)
      ctrl.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
});

使用这个html:

  <body ng-controller="MainCtrl">
    <changecase ng-model="data.name"></changecase>
    <pre>model is: {{data.name}}</pre>
  </body>

我猜这是一个范围或时间问题,但我无法解决。谁能看到我做错了什么?

请在此处随意使用Plunker:http://plnkr.co/edit/FZ4UnW8wIhIwRV2jVvfB?p=preview

1 个答案:

答案 0 :(得分:2)

您遇到的问题非常简单 - 在您的示例中,您有2个模型,一个位于changecase,另一个位于input。你将格式化器添加到第一个,但你需要第二个。所以你的指令应该只是:

app.directive('changecase', function () {
  return {
    restrict: 'E',
    scope: { model: '=model' },
    template: '<input realuppercase type="text" ng-model="model"> {{ model }}',
    link: function (scope, element, attrs) {
    }
  }
});

只是模板,所以你可能想删除它。 (我将ng-model更改为model,因为这里根本不需要ngModel指令) 和新的实例:

app.directive('realuppercase', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {
      ctrl.$formatters.push(function(value) {
        return value.toUpperCase();
      });

      ctrl.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
});

这是你修改过的插件: http://plnkr.co/edit/UoSFFuCVnbAwerQYHc3o?p=preview (输入大写字母 - &gt;小写模型)