获取 Angularjs 自定义指令中的属性值
Get value of attribute in Angularjs custom directive
我要计算文本框中字母的数量,并将其显示在 element 指令的 div 标记中。
<input type="text" ng-model="name">
<div counter-directive max-length="100" ng-model="name"></div>
div 标签必须显示如下内容:12/100(12 是我们输入的内容,100 是 max-length 的值)
问题是,我不知道如何获取最大长度的值。
here 我在 jsfiddle 上有例子
首先,检查你的拼写。您在问题中使用了几次 lenght
。
您可以从传递给 link
函数的 attrs
对象中获取 max-length
属性。
link: function (scope, element, attrs) {
var foo = attrs.maxLength;
}
你只需要这样做:
app.directive('counterDirective', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: { maxLength:'=', ngModel:'&' },
link: function (scope, element, attrs) {
console.log(scope.maxLength);
scope.$watch(scope.ngModel, function (value) {
if (value) {
var newValue = value.length;
console.log(value);
element[0].innerText = newValue;
}
});
}
}
});
我认为您必须将 'lenght' 替换为 'length' :)
我要计算文本框中字母的数量,并将其显示在 element 指令的 div 标记中。
<input type="text" ng-model="name">
<div counter-directive max-length="100" ng-model="name"></div>
div 标签必须显示如下内容:12/100(12 是我们输入的内容,100 是 max-length 的值)
问题是,我不知道如何获取最大长度的值。
here 我在 jsfiddle 上有例子
首先,检查你的拼写。您在问题中使用了几次 lenght
。
您可以从传递给 link
函数的 attrs
对象中获取 max-length
属性。
link: function (scope, element, attrs) {
var foo = attrs.maxLength;
}
你只需要这样做:
app.directive('counterDirective', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: { maxLength:'=', ngModel:'&' },
link: function (scope, element, attrs) {
console.log(scope.maxLength);
scope.$watch(scope.ngModel, function (value) {
if (value) {
var newValue = value.length;
console.log(value);
element[0].innerText = newValue;
}
});
}
}
});
我认为您必须将 'lenght' 替换为 'length' :)