【发布时间】:2016-01-18 01:44:26
【问题描述】:
我正在尝试为输入字段构建一个 characterCounter 属性指令。我的想法是要求:'ngModel' 来获取 ng-model 中 modelValue 的长度,并在指令范围内传递一个 max-length。
<input ng-model="inputModel" max-character-counter max-length="10"/>
我在大多数情况下都有我的指令,我只是在为如何更新视图而苦苦挣扎。非常感谢您提供任何帮助。
angular.module('app').directive('maxCharacterCounter', [function(){
return {
restrict: 'A',
require: '?ngModel',
scope: {
maxLength: "="
},
link: function (scope, elem, attrs, ngModel) {
if (!ngModel) return;
console.log(ngModel);
ngModel.$render = function() {
console.log('render');
var el = angular.element(attrs.$$element);
el.after('<span class="input-group-addon">' + scope.charactersLeft + '</span>');
}
elem.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read();
function read() {
scope.charactersLeft = ngModel.$modelValue.length == undefined ? scope.maxLength : scope.maxLength - ngModel.$modelValue.length;
console.log('Characters Left:', scope.charactersLeft);
console.log('View Value: ', ngModel.$viewValue);
console.log('Model Value: ', ngModel.$modelValue);
updateViewValue();
}
function updateViewValue() {
//How do I update the view for scope.charactersLeft
//ngModel.$viewValue(scope.charactersLeft);
console.log('scope: ', scope);
}
}
}}]);
Plunker:http://plnkr.co/edit/F0PzE6?p=preview
最终解决方案:
angular.module('app').directive('maxCharacterCounter', ['$timeout', '$log', function($timeout, $log) {
return {
restrict: 'A',
require: '?ngModel',
scope: {
maxLength: "@"
},
link: function (scope, elem, attrs, ngModel) {
if (!ngModel) {
$log.warn('ngModel doesn\'t exist. There is no way to calculate characters left');
return;
}
elem.wrap('<div class="input-group"></div>');
elem.after('<span class="input-group-addon"></span>');
elem.on('blur keyup keydown change', function() {
scope.$eval(updateCharacterCount);
updateViewValue();
});
$timeout(function(){
scope.maxLength = scope.maxLength || 140;
scope.$eval(updateCharacterCount);
updateViewValue();
});
function updateCharacterCount() {
scope.charactersLeft = !ngModel.$viewValue ? scope.maxLength : scope.maxLength - ngModel.$viewValue.length;
}
function updateViewValue() {
var element = elem.next('span');
element.text(scope.charactersLeft);
element.toggleClass('redText', scope.charactersLeft <= 0 ? true : false);
}
}
}}]);
【问题讨论】:
-
查看我对模板使用示例的回答。如果您遇到其他问题。告诉我
标签: angularjs twitter-bootstrap