16

たとえば、AngularJS が「メール」を実装する方法と同様のカスタム入力タイプを作成したいと思います。

<input type="email" ng-model="user.email" />

私が作成したいのは、次のような入力タイプです。

<input type="path" ng-model="page.path" />

これをどのように達成できるかについてのアイデアはありますか? これまでのところ、'path' がタグ、属性、またはクラスの名前であるカスタム ディレクティブを実装する方法しか理解できていません。

たとえば、これを機能させることはできますが、他のフォーム フィールドと一貫性がなく、同じように見せたいと思っています。

<input type="text" ng-model="page.path" path />
app.directive('path', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) { ... }
  };
});
4

3 に答える 3

18

type 属性が「path」に設定されている場合、カスタム ロジックを使用して入力ディレクティブを作成することにより、独自の input type="path" を作成できます。

に置き換えるだけの簡単な例を作成しまし\/。ディレクティブは次のようになります。

module.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (attr.type !== 'path') return;

          // Override the input event and add custom 'path' logic
          element.unbind('input');
          element.bind('input', function () {
            var path = this.value.replace(/\\/g, '/');

            scope.$apply(function () {
              ngModel.$setViewValue(path);
            });
          });
        }
    };
});

Example

更新: を に変更onoffbindunbindjQuery の依存関係を削除しました。例を更新しました。

于 2013-02-06T19:33:20.747 に答える
2

ngModelController$parsersのプロパティを使用して、代替ソリューションを実現できます。このプロパティは、検証に渡す (そして最終的にモデルに割り当てる) 前に、入力コンポーネントの値に適用される一連のパーサーを表します。これにより、ソリューションは次のように記述できます。

module.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (attr.type !== 'path') return;

          ngModel.$parsers.push(function(v) {
            return v.replace(/\\/g, '/');
          });
        }
    };
});

$formattersモデル値を入力に表示される値に変換するフォーマッターのパイプラインである別のプロパティがあることに注意してください。

プランカーについてはこちらをご覧ください。

于 2015-08-17T14:20:16.750 に答える
0

コンパイル関数が最初にあることを考えると、次のほうがよいでしょうか。

module.directive('input', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    compile: function Compile(tElement, tAttrs) {
      if (tAttrs.type !== 'path') return;

      return function PostLink(scope, element, attr, ngModel) {
        // Override the input event and add custom 'path' logic
        element.unbind('input');
        element.bind('input', function () {
          var path = this.value.replace(/\\/g, '/');

          scope.$apply(function () {
            ngModel.$setViewValue(path);
          });
        });
      }
    }
  };
});
于 2016-08-24T14:36:00.043 に答える