【发布时间】:2013-08-15 09:16:48
【问题描述】:
我想要实现的是为输入字段添加额外的界面,以便能够通过单击 + 和 - 按钮来增加和减少其中的数值。
(本质上它是 chrome 上的 input[type=number] 字段,但我希望它能够跨浏览器兼容,并且还可以完全控制所有浏览器的呈现)。
查看代码:
<input data-ng-model="session.amountChosen" type="text" min="1" class="form-control input-small" data-number-input>
指令代码:
app.directive('numberInput', function() {
return {
require: 'ngModel',
scope: true,
link: function(scope, elm, attrs, ctrl) {
var currValue = parseInt(scope.$eval(attrs.ngModel)),
minValue = attrs.min || 0,
maxValue = attrs.max || Infinity,
newValue;
//puts a wrap around the input and adds + and - buttons
elm.wrap('<div class="number-input-wrap"></div>').parent().append('<div class="number-input-controls"><a href="#" class="btn btn-xs btn-pluimen">+</a><a href="#" class="btn btn-xs btn-pluimen">-</a></div>');
//finds the buttons ands binds a click event to them where the model increase/decrease should happen
elm.parent().find('a').bind('click',function(e){
if(this.text=='+' && currValue<maxValue) {
newValue = currValue+1;
} else if (this.text=='-' && currValue>minValue) {
newValue = currValue-1;
}
scope.$apply(function(){
scope.ngModel = newValue;
});
e.preventDefault();
});
}
};
})
这可以通过scope.$eval(attrs.ngModel)获取当前模型值,但是设置新值失败。
事后编辑:这是现在可以工作的代码(以防你不想看到这个问题的解决方案)
app.directive('numberInput', function() {
return {
require: 'ngModel',
scope: true,
link: function(scope, elm, attrs, ctrl) {
var minValue = attrs.min || 0,
maxValue = attrs.max || Infinity;
elm.wrap('<div class="number-input-wrap"></div>').parent().append('<div class="number-input-controls"><a href="#" class="btn btn-xs btn-pluimen">+</a><a href="#" class="btn btn-xs btn-pluimen">-</a></div>');
elm.parent().find('a').bind('click',function(e){
var currValue = parseInt(scope.$eval(attrs.ngModel)),
newValue = currValue;
if(this.text=='+' && currValue<maxValue) {
newValue = currValue+1;
} else if (this.text=='-' && currValue>minValue) {
newValue = currValue-1;
}
scope.$eval(attrs.ngModel + "=" + newValue);
scope.$apply();
e.preventDefault();
});
}
};
})
【问题讨论】:
-
可能是
ctrl.$setViewValue(newValue)? -
使用 ng-click 和模板。
-
Cherniv,不,它没有起到作用,但你的建议帮助我更好地理解了 Angular。谢谢。
标签: angularjs angularjs-directive angularjs-scope