Dynami c тип ввода angularjs - PullRequest
       0

Dynami c тип ввода angularjs

0 голосов
/ 21 февраля 2020
<!doctype html>
<html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Example - example-input-directive-production</title>        
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
    </head>

    <body ng-app="inputExample">
    <div ng-controller="ExampleController">
      <form name="myForm">
         <label>
           Is Bulk:
        <input type="checkbox" ng-model="isBulk" ng-change="onChange()"/>
        </label
        <label>
           Quantity:
           <input input-type="isBulk ? 'text' : 'number'" name="lastName"
                  ng-model="quantity"
                  ng-minlength="3" ng-maxlength="10"
                  ng-disabled="isBulk"
           >
        </label>
      </form>
        <hr/>
        <div>isBulk:{{isBulk}}</div>
         <div>quantity: {{quantity}}</div>
    </div>
    </body>
</html>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
   $scope.quantity = 0;
   $scope.isBulk = false;
   $scope.onChange = function(){
     if($scope.isBulk){
        $scope.quantity = "NOT APPLICABLE";
     }else{
        $scope.quantity = 0;
     }
   }
}])
.directive('inputType', function() {
    return {
      restrict: "A",
      scope: {
        quantity: "="
      },
      link: function(scope, element, attr) {
        var inputType = scope.$eval(attr.inputType);
        console.log("inputType", inputType);
        element.attr("type", inputType);
      }
    };
});

Как динамически изменить тип ввода на основе значения.

Вот ссылка на плункер

https://next.plnkr.co/edit/kmkNKPWcM5jq159k

Ответы [ 2 ]

0 голосов
/ 21 февраля 2020

Измените директиву для просмотра выражения атрибута:

app.directive('inputType', function() {
    return {
      restrict: "A",
      link: function(scope, elem, attrs) {
      ̶s̶c̶o̶p̶e̶:̶ ̶{̶
          ̶i̶n̶p̶u̶t̶T̶y̶p̶e̶:̶ ̶=̶
      ̶}̶,̶ 
      link: function(scope, elem, attrs) {          
        ̶v̶a̶r̶ ̶i̶n̶p̶u̶t̶T̶y̶p̶e̶ ̶=̶ ̶s̶c̶o̶p̶e̶.̶$̶e̶v̶a̶l̶(̶a̶t̶t̶r̶.̶i̶n̶p̶u̶t̶T̶y̶p̶e̶)̶;̶
        scope.$watch(attrs.inputType, function(newValue) {
            var inputType = newValue;
            console.log("inputType", inputType);
            elem.attr("type", inputType);
        });
      }
    };
});

Затем директива будет обновляться при изменении значения выражения.

Примечание: При наличии наблюдатель оценивает атрибут напрямую, директива избегает использования изолированной области видимости для оценки атрибута.

0 голосов
/ 21 февраля 2020

Используйте другой шаблон с ng-if

<input ng-if="isBulk" input-type="text" name="lastName" ng-model="quantity"
       ng-minlength="3" ng-maxlength="10">
<input ng-if="!isBulk" input-type="number" name="lastName" ng-model="quantity"
       ng-minlength="3" ng-maxlength="10">

Обновление

Вы можете добавить наблюдателя в вашу директиву:

scope.$watch("inputType", function (newValue, oldValue, scope) {
    if (newValue && newValue !== oldValue) {
        element.attr("type", newValue);
    }
});

Плункер: https://next.plnkr.co/edit/EsTwRTChBHjDqD2e

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...