Input.js 2.74 KB
import style from "antd/lib/input/style/index.css";
angular.module("esNgAntd").directive("antdInput", ["$compile", "esNgAntd", function ($compile, esNgAntd) {
  return {
    restrict: "E",
    replace: true,
    transclude: true,
    scope: {
      value: "@",
      placeholder: "@",
      addonBefore: "@",
      addonAfter: "@",
      disabled: "=",
      onChange: "&",
      maxLength: "="
    },
    require: ["^?antdFormItem", "^?antdForm"],
    controller: function ($scope, $element, $attrs) {
      $scope.state = {
        inputEventTarget: null
      };

      $scope.handleClick = function (event) {
        $scope.state.inputEventTarget = event;
      };

      $scope.handleChange = function () {
        $scope.onChange({
          event: $scope.state.inputEventTarget
        });
      };

      $scope.getTemplate = function () {
        let maxLengthAttribute = "";
        let styleAttribute = "";
        let idAttribute = "";

        if ($scope.maxLength) {
          maxLengthAttribute = `maxlength="${$scope.maxLength}"`;
        }

        if ($scope.style) {
          styleAttribute = `style="${$scope.style}"`;
        }

        if ($scope.antdFormItem && $scope.antdFormItem.name) {
          idAttribute = `id="${$scope.antdFormItem.name}"`;
        }

        let templates = [`<input type="text" class="ant-input" placeholder={{placeholder}} ng-change="handleChange()" ng-model="value" ng-focus="handleClick($event)" ng-disabled="disabled===true" ${styleAttribute} ${maxLengthAttribute} ${idAttribute}/>`, `<span class="ant-input-group-wrapper" ng-if="addonBefore||addonAfter">
        <span class="ant-input-wrapper ant-input-group" style="">
            <span class="ant-input-group-addon" ng-if="addonBefore">{{addonBefore}}</span>
            <input type="text" class="ant-input" ng-change="handleChange()" ng-model="value" ng-focus="handleClick($event)" ng-disabled="disabled===true" style="${$scope.style}" ${styleAttribute} ${maxLengthAttribute} ${idAttribute}/>
            <span class="ant-input-group-addon" ng-if="addonAfter">{{addonAfter}}</span>
        </span>
    </span>`];

        if ($scope.addonBefore || $scope.addonAfter) {
          return templates[1];
        } else {
          return templates[0];
        }
      };
    },
    link: function ($scope, $element, $attrs, $controllers) {
      let [antdForm, antdFormItem] = $controllers;
      esNgAntd.createStyle("ant-input", style);

      if (antdFormItem) {
        $scope.antdFormItem = antdFormItem.getContext();
      } // 上下文


      if (antdForm) {
        $scope.antdForm = antdForm.getContext();
        $scope.antdForm.state.formItems.push($scope);
      }

      $scope.style = $attrs.style;
      $element.replaceWith($compile($scope.getTemplate())($scope));
    }
  };
}]);