2016-04-23 14 views
0

私はカスタムディレクティブなどのAngularJSの高度な機能を探求しています。カスタムディレクティブを使用することによって、ドロップダウンボックスからユーザーが選択した値に応じて数値のみまたはテキストのみを許可するテキストボックスを作成したいと考えています。私はAngularJs Custom Directive fails the text box validationに基づいてのみ番号を許可するカスタムディレクティブを作成することができました。同じテキストボックスにカスタムディレクティブを動的に適用する方法がわかりません。私は、テキストのみを許可する別のカスタム指示文を作成しましたが、数字のみの指示文をテキストのみの指示文で動的に置き換える方法を明確にしていません。カスタム角度指示を動的に適用するにはどうすればよいですか?

<body> 
<div ng-app="TextboxExample" ng-controller="ExampleController"> 
    <form name="shippingForm" novalidate> 
     <select id="textBoxOptions" > 
      <option value="number" selected="selected">Numbers Only</option> 
      <option value="text">Text Only</option> 
      <option value="special">Special Characters</option> 
      <option value="any">Any Value</option> 
     </select> 

     <input id="customTextBox" unbindable number-only-input type="text" name="name" ng-model="testvalue.number" required /> 
     <span class="error" ng-show="shippingForm.name.$error.required"> 
      Please enter a value 
     </span> 
    </form> 
</div> 
<script src="scripts/angular.js"></script> 
<script src="scripts/jquery.min.js"></script> 
<script>  
    $("select").change(function() { 

     var selected = $("#textBoxOptions").val(); 
     $('#customTextBox').attr("ng-model", selected); 
    }); 
</script> 
<script> 

    angular.module('TextboxExample', []) 
    .controller('ExampleController', ['$scope', function ($scope) { 
     $scope.testvalue = { number: 1, validity: true }; 
    }]) 
    .directive('numberOnlyInput', ['$compile', function ($compile) { 
     return { 

      link: function (scope, element, attrs) { 
       var watchMe = attrs["ngModel"]; 
       scope.$watch(watchMe, function (newValue, oldValue) { 
        if (newValue == undefined || newValue == null || newValue == "") { 
         return; 
        } else if (isNaN(newValue)) { 
         var myVal = watchMe.split("."); 
         switch (myVal.length) { 
          case 1: 
           scope[myVal[0]] = oldValue; 
           break; 
          case 2: 
           scope[myVal[0]][myVal[1]] = oldValue; 
         } 
        } 

        $compile(element)(scope); 
       }); 

      } 
     }; 

    }]); 
</script> 

私はドロップダウンボックスで値を変更した場合の検査要素によって確認されたとして、それが正しくcustomTextBox上NG-モデルを変更します。しかし、複数のディレクティブを作成して適用する方法がわかりません。ありがとう

+0

属性

<input ng-show="yourmode" number-directive ng-model="data"> <input ng-show="!yourmode" text-directive ng-model="data"> 

<input {{ yourmode ? number-directive : text-directive }} ng-model="data"> 

または

か、ダイナミックディレクティブでモードを変更する:あなたはディレクティブatttibuteまたは全部の要素を切り替えることができます条件付きでng-classを使用します。 :) –

答えて

1

いくつかの可能性があります。単にクラスとしてそのディレクティブを作成し、そのクラスを使用

<input directive-data="yourmode" my-input-directive ng-model="data"> 
+0

サイモン、私は最初のアプローチが好きです。 2つ以上のオプションがある場合はどうなりますか?数字だけ、テキストのみ、特殊文字のみ – Massey

+0

@drifter。それでは、あなたのモードに応じて属性値を変更するためのディレクティブを使用しないのはなぜですか? –

関連する問題