我正在探索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-模型。但是,我不確定如何創建和應用多個指令。謝謝
只需創建該指令爲類,並使用該類有條件地使用ng-class。 :) –