AngularJS Conditionally added attribute
this is a small fiddle with a quite special timer
by rahilwazir
HTML
<div ng-app="MyApp" ng-controller="ctrl">
<input type="text" max-length="{{max_length}}" my-element />
</div>
JavaScript
var App = angular.module('MyApp', []);
App.controller('ctrl', function($scope) {
$scope.max_length = 0;
});
App.directive('maxlengthCounter', function ($compile, $parse) {
return {
require: 'ngModel',
scope: {},
link: function (scope, element, attrs, ngModel) {
var maxLength = parseInt(attrs.maxLength, 10);
if (maxLength) {
element.bind("keyup", function () {
var value = element[0].value;
element.val(value.substr(0, maxLength));
});
}
}
};
});
App.directive('myElement', function ($compile) {
return {
restrict: "A",
scope: {},
link: function (scope, element, attrs, ngModel) {
(attrs.maxLength > 0 ? angular.element(element[0]).attr("maxlength-counter", "") : '');
$compile(element.html())(scope);
}
};
});