AngularJS NG-模式选项消气二传手 [英] AngularJS ng-model-options getter-setter
问题描述
我刚刚升级到版本角1.3.8。
I've just upgrade to angular version 1.3.8.
在使用1.2.23版本,我创建了一个指令转换数据表单视图模型,反之亦然。
When using 1.2.23 version I've created a directive to convert the data form view to model and vice verse.
这是我的指令:
.directive('dateConverter', ['$filter', function ($filter) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelController) {
// Convert from view to model
ngModelController.$parsers.push(function (value) {
return $filter('date')(new Date(date), 'yyyy-MM-ddTHH:mm:ss')
});
// Convert from model to view
ngModelController.$formatters.push(function (datetime) {
return $filter('date')(datetime, 'MM/dd/yyyy');
});
}
};
}]);
});
我看到这里的干将并结合制定者现在都支持,但我找不到任何地方如何使用两个干将和 setter方法。有没有办法做到这一点?这是 - ?可以NG-模式选项取代我的转换指令
I see here that getters and setters in binding are now supported, but I cannot find anywhere how to use both getters and setters. Is there any way to do it? That is - can ng-model-options replace my convert directive?
感谢
推荐答案
该文档似乎有点模糊,但用法相当简单。
你需要做什么:
The documentation might seem a bit fuzzy but the usage is quite simple. What you need to do:
-
HTML:
HTML:
<input ng-model="pageModel.myGetterSetterFunc"
ng-model-options=" {getterSetter: true }">
在JS控制器,而不是实际的模型中,创建将返回值的函数(+申请汽提),如果没有发送参数和将更新模型(+应用其他的变化),如果参数发送。
in JS controller, instead of the actual model, create a function that will return the value (+ apply stripping) if the there is no parameter sent and that will update the model (+ apply other changes) if a parameter is sent.
本的getter / setter方法基本上是认为价值和模型价值之间的另一个层。
The getter/setters is basically another "layer" between the view value and model value.
例如:
$scope.pageModel.firstName = '';
$scope.pageModel.myGetterSetterFunc: function (value) {
if (angular.isDefined(value)) {
$scope.pageModel.firstName = value + '...';
} else {
return $scope.pageModel.firstName.substr(0,
$scope.pageModel.firstName.lastIndexOf('...')
);
}
}
DEMO PLUNKER:
<一href=\"http://plnkr.co/edit/Zyzg6hLMLlOBdjeW4TO0?p=$p$pview\">http://plnkr.co/edit/Zyzg6hLMLlOBdjeW4TO0?p=$p$pview
(检查控制台 - http://screencast.com/t/3SlMyGnscl )
(check console - http://screencast.com/t/3SlMyGnscl)
请注意:看到这将是有趣的怎么会有如此规模的可重用性方面。我建议来创建这些吸气/ setter方法作为外在可重复使用的方法和具有发电机它们(因为该数据模型是对于每种情况不同)。并在控制器只调用这些发电机。只是我的2美分。
NOTE: It would be interesting to see how would this scale in terms of reusability. I would advise to create these getter/setters as externalized reusable methods and have generators for them (because the data model is different for each case). And in controllers to only call those generators. Just my 2 cents.
这篇关于AngularJS NG-模式选项消气二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!