Skip to content

Instantly share code, notes, and snippets.

@ocombe
Created June 13, 2013 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ocombe/5773738 to your computer and use it in GitHub Desktop.
Save ocombe/5773738 to your computer and use it in GitHub Desktop.
Angular directive for limited textarea (limited in number of octets in this case)
angular.module('grid').
directive('limitedtextarea', function () {
var byteLength = function (s, b, i, c) {
for (b = i = 0; c = s.charCodeAt(i++); b += c >> 11 ? 3 : c >> 7 ? 2 : 1);
return b;
}
return {
restrict: 'E',
replace: true,
require: '?ngModel', // get a hold of NgModelController
scope: {
data: '=ngModel',
max: '@ngMax',
id: '@ngId'
},
template: '<div><textarea ng-model="data" id="{{id}}" ng-change="checkData()" placeholder="..."></textarea> <span class="alert {{class}}" style="padding: 8px;">{{length}}/{{max}} {{type}}</span></div>',
link: function ($scope, $element, attrs, ngModel) {
$scope.type = attrs.ngType;
$scope.length = byteLength($scope.data || '');
$scope.class = "alert-success";
$scope.checkData = function() {
var len = byteLength($scope.data);
if(len > attrs.ngMax) {
var data = $scope.data;
while(len > attrs.ngMax) {
data = data.substr(0, data.length-1);
len = byteLength(data);
}
$scope.data = data;
$scope.length = len;
}
if(len == attrs.ngMax) {
$scope.length = len;
$scope.class = "alert-error";
} else {
$scope.length = len;
$scope.class = "alert-success";
}
}
}
}
});
<limitedtextarea ng-model="notification.msg" ng-id="notifMsg" ng-type="octets" ng-max="200"></limitedtextarea>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment