gpt4 book ai didi

templates - AngularJS - 在自定义指令中渲染模板之前格式化 ng-model

转载 作者:行者123 更新时间:2023-12-02 21:34:25 25 4
gpt4 key购买 nike

我正在 Angular JS 中创建自定义指令。我想在模板渲染之前格式化 ng-model。

这是我到目前为止所拥有的:

app.js

app.directive('editInPlace', function() {
return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});

html

<edit-in-place ng-model="unformattedDate"></edit-in-place>

我想在将 unformattedDate 值输入模板的 ngModel 之前对其进行格式化。像这样的事情:

template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'

但这给了我一个错误。如何做到这一点?

最佳答案

ngModel 公开其 Controller ngModelController API并为您提供了一种方法。

在您的指令中,您可以添加 $formatters这正是您所需要的并且 $parsers ,则以相反的方式执行(在将值传递到模型之前解析该值)。

这就是你应该走的路:

app.directive('editInPlace', function($filter) {
var dateFilter = $filter('dateFormat');

return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
link: function(scope, element, attr, ngModelController) {
ngModelController.$formatters.unshift(function(valueFromModel) {
// what you return here will be passed to the text field
return dateFilter(valueFromModel);
});

ngModelController.$parsers.push(function(valueFromInput) {
// put the inverse logic, to transform formatted data into model data
// what you return here, will be stored in the $scope
return ...;
});
},
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});

关于templates - AngularJS - 在自定义指令中渲染模板之前格式化 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15901889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com