[英]Using ng-init and ng-model together
Hi I have situation where I have to format certain values using ng-init as well as have ng-model for two way binding in input field so value can be changed and saved. 嗨,我有这样一种情况,我必须使用ng-init格式化某些值,并且必须在输入字段中使用ng-model进行双向绑定,因此可以更改和保存值。
<div ng-repeat="ab in ablist">
<div class="col-sm-3">
<input type="text" ng-init="item.ab=fn(item.ab)" ng-model="item.ab" />
</div>
</div>
The above code doesnt work. 上面的代码不起作用。 It does not show the formatted value. 它不显示格式化值。 Can you let me know how I can change this so I can display the formatted value using ng-init but as well as keep ng-model for binding edited value on submit. 您能否让我知道如何更改此设置,以便可以使用ng-init显示格式化的值,还可以保留ng-model以便在提交时绑定已编辑的值。
In this case you have to use directive. 在这种情况下,您必须使用指令。 ng-init is to be used when you want to set some default or initial value to any control. 想要为任何控件设置一些默认值或初始值时,将使用ng-init。 Directive can keep your display value and your model value in separate formats. 指令可以将您的显示值和模型值保持在单独的格式中。 Here is a directive for formatting integers with commas. 这是使用逗号格式化整数的指令。
app.directive('formattednumber', function () {
return {
link: function (scope, element, attrs, ctrl) {
element.bind('blur', function (blurEvent) {
if (element.data('old-value') !== element.val()) {
// console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
var v = number_format(element.val(), 0, 0, 99999999999);
element.val(v);
//scope.myDirective = element.val();
//element.data('old-value', element.val());
});
}
});
ctrl.$formatters.unshift(function (modelValue) {
if(!modelValue) modelValue="0";
if(modelValue.replace &&(isNaN(parseFloat(modelValue)) || !isFinite(modelValue)))
{
modelValue = parseFloat(modelValue.replace(/,/g, ""));
}
var v = number_format(modelValue, 0, 0, 99999999999);
v = v == undefined? 0 : v;
element.val(v);
return v;
});
ctrl.$parsers.unshift(function (viewValue) {
if(!viewValue) viewValue="0";
viewValue = parseInt(viewValue.replace(/,/g, ""));
var v = number_format(viewValue, 0, 0, 99999999999);
v = v == undefined? 0 : v;
element.val(v);
return viewValue;
});
},
restrict: 'A',
require: 'ngModel'
}
});
Similarly, you can write one for date formatting. 同样,您可以编写一个日期格式。 You can use Date.js for the same. 您可以使用Date.js进行相同的操作。
The usage is : 用法是:
<input type="text" ng-model="item.amount" formattednumber />
What about this: 那这个呢:
<div ng-repeat="ab in ablist">
<div class="col-sm-3">
<input type="text" ng-init="item=fn(ab)" ng-model="item" />
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.