如何使用选择组件

时间:2017-12-04 18:48:16

标签: javascript angularjs angularjs-directive ng-options

我想向后端发送模型值的属性。为此,我有一个指令,用于绘制一个带有所有可选值的选择输入

上下文:我们将Grails域类定义为

class Example {
    String name
    EnumObject desiredToTransform
}

有一个GET Rest服务将此对象的实例的JSON返回为:

{
    "id": 1,
    "name": "Albert"
    "desiredToTransform": {
         "id": "EXAMPLE_ID",
         "label":"Example value"
    }
}

此对象的create Rest服务接收以下参数:[name: String, desiredToTransform:String]。如果我们想要创建此实例的对象,我们必须执行以下操作:

curl -X POST <POST_URL> -d '{"name":"Jhon Doe", "desiredToTransform":"EXAMPLE_ID"}'

问题: 我找到的解决方案是创建一个接收模型并根据需要转换结果的指令

A plunker with the solution can be found here,并在片段

上显示

// Code goes here
var app = angular.module("app", []);

function rselectForEnum($http, $compile) {
  return {
    link: function(scope, elem, attrs) {
      var parent = angular.element(elem.parent());
      var enumerativo = attrs.enum || attrs['data-enum'] || "";
      var idElem = attrs["id"] || new Date().getTime().toString();
      var nameElem = attrs["name"] || idElem;
      var modeloElem = attrs.ngModel;
      if (typeof modeloElem === "undefined") {
        throw Error("De especificar el modelo");
      }
      //The original data receive a parameter for a REST service in order to gather the data
      // $http.get(config.apiUrl + "enumerativo/getEnum?c=" + enumerativo).then(function (response) {
      //     scope[nameElem + "EnumList"] = response.data.lista;
      // }, function (response) {
      // });

      //I am going to replace it with this code
      scope[nameElem + "EnumList"] = [{
        id: "EXAMPLE_1",
        label: "Exampple 1"
      }, {
        id: "EXAMPLE_2",
        label: "Exampple 2"
      }, {
        id: "EXAMPLE_3",
        label: "Exampple 3"
      }, {
        id: "EXAMPLE_4",
        label: "Exampple 4"
      }, {
        id: "EXAMPLE_5",
        label: "Exampple 5"
      }, ]


      var htmlSelect = "<select id='" + idElem + "' " +
        "name='" + nameElem + "' " +
        " class='form-control'>" +
        "</select>";
      var elemento = angular.element(htmlSelect);
      elemento.attr("data-ng-model", attrs.ngModel);
      elemento.attr("ng-options", "item.id as item.label for item in " + nameElem + "EnumList track by item.id");
      parent.append(elemento);
      elem.remove();
      $compile(parent)(scope);
    }
  }
}

app.directive('rselectforenum', ['$http', '$compile', rselectForEnum]);

app.controller("PruebaController", PruebaController);

/*@ngInject*/
function PruebaController($scope) {

  var vm = this;

  $scope.modelo = {
    enumerativo: {
      "id": "EXAMPLE_2",
      "label": "Example 2"
    }
  };

  vm.wizzard = {

  };

  init();
  return vm.wizzard;

  function init() {
    // initialize tuffs here
  }
}
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js
"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>How to transform the model with a select component?</h1>
    
    <div ng-controller="PruebaController">
    <div class="row">
    <div class="col-md-3">
        <label class="">Probando</label>
        <div class="form-line">
            <rselectForEnum
                    id="rselectForEnumId"
                    data-ng-model="modelo.enumerativo"
                    enum="EstadoCivil"
            ></rselectForEnum>
        </div>
    </div>
</div>

<div class="row">
  This is the value: 
    {{modelo.enumerativo}}
</div>
<br/>
<div class="row">
  This is the list:<br/>
    {{rselectForEnumIdEnumList}}
</div>

</div>

  </body>

</html>

结果导致以下行为:

  1. 加载内容后,将使用模型值( DESIRED
  2. 选择选择输入
  3. 模型保持原始值(不希望
  4. 在更改值时,模型获得了id属性( DESIRED
  5. 首次修改时,标签会变为空白,但值是正确的(不希望
  6. 如果您不更改选择并将表单发送到后端,则会发送原始值(不希望
  7. 我该如何解决这个问题?

0 个答案:

没有答案