Checkbox.js 1.95 KB
import style from "antd/lib/checkbox/style/index.css";
import template from "./Checkbox.html";
angular.module("esNgAntd").directive("antdCheckbox", ["esNgAntd", function (esNgAntd) {
  return {
    template: template,
    restrict: "E",
    replace: true,
    transclude: true,
    scope: {
      defaultChecked: "=",
      checked: "@",
      disabled: "@",
      onChange: "&"
    },
    require: ["^?antdForm", "^?antdFormItem"],
    controller: function ($scope, $element) {
      $scope.watch = {
        checked: function (newVal) {
          if (newVal !== undefined) {
            $scope.state.checked = ["true", "checked", true].includes(newVal) ? true : false;
          }
        },
        disabled: function (newVal) {
          if (newVal !== undefined) {
            $scope.state.disabled = ["true", "disabled", true].includes(newVal) ? true : false;
          }
        }
      };
      $scope.state = {
        checked: $scope.checked || $scope.defaultChecked || false,
        disabled: false,
        type: "checkbox"
      };

      $scope.handleClick = function ($event) {
        if ($scope.state.disabled) {
          return;
        }

        $scope.state.checked = !$scope.state.checked;
        $scope.onChange({
          event: $event
        });
      };

      $scope.setValue = function (value) {
        if (value) {
          $scope.state.checked = value;
        } else {
          $scope.state.checked = false;
        }
      };
    },
    link: function ($scope, $element, $attrs, $controllers) {
      for (const key in $scope.watch) {
        $scope.$watch(key, $scope.watch[key], true);
      }

      let [antdForm, antdFormItem] = $controllers;
      esNgAntd.createStyle("ant-checkbox", style); // 上下文

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

      if (antdFormItem) {
        $scope.antdFormItem = antdFormItem.getContext();
      }
    }
  };
}]);