AngularJs-将一个ng模型绑定到具有两个输入的指令
AngularJs - bind one ng-model to directive with two inputs
如何创建一个绑定到一个ng-model
并使用filter
输出两个input
字段的range
指令(已制作(。本质上,我有一个方向从模型到输入工作,但另一个方向从输入到模型则不然。如何做到这一点?
我有这个Html:
<div tu-range ng-model="arbitraymodel" />
和一个模型:
var arbitrarymodel = "10/22";
旁注;我创建了一个过滤器来分割这两个值:{{ feature.Value | split:''/'':0}}
这个指令:
.directive('tuRange', function($compile) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
feature: '=',
tudisabled: '=',
model: '=ngModel' // edited
},
template: '<input type="text" '+
'ng-value="{{ model | split:''/'':0}}" />'+ // edited to 'model'
'-<input type="text" '+
'ng-value="{{ model | split:''/'':1}}" />', // edited to 'model'
link: function(scope, element, attributes, ngModel) {
}
};
})
正确的方法(IMO(是按照此处所述创建自定义控件。
作为练习,我在小提琴中实现了它:http://jsfiddle.net/6cn7y/
指令的代码是(您可能需要调整一些细节(:
app.directive("range", function() {
var ID=0;
function constructRangeString(from, to) {
var result;
if( !from && !to ) {
result = null;
}
else if( from ) {
result = from + "/" + (to || "");
}
else if( to ) {
result = "/" + to;
}
return result;
}
return {
require: "ngModel",
restrict: "E",
replace: true,
scope: {
name: "@"
},
template:
'<div ng-form="{{ subFormName }}">' +
'<input type="text" ng-model="from" class="range-from" />' +
'<input type="text" ng-model="to" class="range-to" />' +
'</div>',
link: function(scope,elem,attrs,ngModel) {
var re = /([0-9]+)'/([0-9]+)/;
if( scope.name ) {
scope.subFormName = scope.name;
}
else {
scope.subFormName = "_range" + ID;
ID++;
}
ngModel.$render = function() {
var result, from, to;
result = re.exec(ngModel.$viewValue);
if( result ) {
from = parseInt(result[1]);
to = parseInt(result[2]);
}
scope.from = from;
scope.to = to;
};
scope.$watch("from", function(newval) {
var result = constructRangeString(newval, scope.to);
ngModel.$setViewValue(result);
});
scope.$watch("to", function(newval) {
var result = constructRangeString(scope.from, newval);
ngModel.$setViewValue(result);
});
}
};
});
它的用法是:
<range ng-model="ctrl.theRange" name="myRange" required="true"></range>
我怀疑过滤器是否能让你在这方面取得进展,因为它们不进行双向绑定。
EDIT:尽管这解决了问题,但我建议使用稍微不同的方法。我将把range
指令的模型定义为一个对象:
{
from: ...,
to: ...
}
这意味着示例中ctrl.theRange
变量中的输出将是类似于上面的对象。如果您确实想要字符串格式"from/to"
,请在ngModel
管道中添加一个解析器/格式化程序,即constructRangeString()
函数。使用解析器/格式化程序,ctrl.theRange
变量获得所需的字符串格式,同时保持代码更加模块化(constructRangeString()
函数在指令外部(和更加参数化(模型的格式易于处理和转换(。
以及概念验证:http://jsfiddle.net/W99rX/
相关文章:
- javascript函数,它接受两个输入:一个对象和一个键,并返回对象中该键的相应值
- 比较jquery中的两个输入
- 使用javascript将两个输入的日期添加在一起
- 如何将(a*b)两个输入文本值相乘,并在javascript中随文本变化动态显示
- 比较两个输入字段
- 在 JavaScript 中计算两个输入字段值
- 在 ng 模型中具有单向绑定的两个输入
- 比较两个输入值的 AngularJS 无法按预期工作
- 有两个输入的表单未提交
- 点击页面刷新;重新显示两个输入元素
- 无法破解pass-css插件以使两个输入元素出现在一行中
- 一种在javascript上获得具有两个输入(字符串)的散列键的方法
- 获取两个输入元素的值,并检查第三个元素的值.将值设置为第四个元素
- 如何在JavaScript中关联两个输入
- 使用jquery计算提取数据的两个输入值
- 验证两个输入之间的一个输入
- 使用javascript获取两个输入范围的值
- 节点js可以计算两个输入字段的值并更新另一个字段吗?
- 输入两个输入,填写第三个
- JavaScript 在两个输入中计算错误的百分比