Created
June 13, 2013 13:37
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} | |
} | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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