如何动态应用自定义角度指令?

时间:2016-04-23 21:03:10

标签: javascript angularjs

我正在探索AngularJS中的高级功能,例如自定义指令。我希望有一个文本框,通过使用自定义指令,应该只允许数字或文本,具体取决于用户从下拉框中选择的值。我已设法创建一个自定义指令,该指令仅允许基于AngularJs Custom Directive fails the text box validation的数字。我不确定如何动态地将自定义指令应用于同一文本框。我创建了另一个自定义指令,该指令只允许文本,但不确定如何动态地将仅数字指令替换为text only指令。

<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-model,并由inspect元素检查。但是,我不确定如何创建和应用多个指令。感谢

1 个答案:

答案 0 :(得分:1)

有几种可能性。您可以切换指令atttibute或整个元素:

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

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

或者您使用动态指令属性

更改模式
<input directive-data="yourmode" my-input-directive ng-model="data">