如何在没有表单和指令的情况下从控制器内部访问 $ngModelController [英] How to access the $ngModelController from inside the Controller without a Form and without a Directive
问题描述
也许这是一个菜鸟的错误,但我似乎无法访问 $scope.model
的 $ngModelController
所以我可以获取 $viewValue
来自它.
Maybe it's a rookie mistake, but I can't seem to access the $scope.model
's $ngModelController
so I can grab the $viewValue
from it.
我有一个没有表单的输入(我使用 ui-mask 指令):
I have an input without a form (im using ui-mask directive):
<input type="text" ng-model="inicio" name="inicio" ui-mask="99/99/9999">
// inside my controller
$scope.inicio = dateFilter((new Date).getTime(), 'dd/MM/yyyy');
ui-mask 将 $modelValue 设置为与 $viewValue 不同的值,从而难以将格式化数据发送到服务器.当 $scope.inicio
模型更改时,该值是一个没有斜线的日期,例如 01012014
.所以我需要能够获得该输入的控制器,但不必将其包装在表单中,并且必须使用 $scope.myForm.inicio.$viewValue
.一定有可能...
ui-mask set the $modelValue a different value than $viewValue, making it hard to send formatted data to the server. When the $scope.inicio
model changes, the value is a date without slashes, like 01012014
. So I need to be able to get the controller for that input, but without having to wrap it in a form, and have to use $scope.myForm.inicio.$viewValue
. It MUST be possible...
我知道我可以做的事情,但看起来很笨拙,必须有一个更简单的方法:
Things I know I can do, but seems hacky, there must be a simpler way:
- 将元素放入表单中并通过
$scope.myForm.input.$viewValue
访问它 - 使用 jQuery 获取元素数据
$('input[name="inicio"]').data('$ngModelController');
- 使用
angular.element('input[name="inicio"]').controller('ngModel');
获取元素 - 创建一个指令,将其放入输入中,并用它更新我的范围模型
app.directive('viewValue', function(){
return {
priority: 10,
require: 'ngModel',
link: function(scope, element, attrs, controller){
scope.$watch(attrs.viewValue, function(newValue, oldValue){
if (newValue !== oldValue){
scope[attrs.viewValue] = controller.$viewValue;
}
});
}
}
});
<input type="text" ui-mask="99/99/9999" ng-model="inicio" view-value="inicio">
推荐答案
我喜欢指令替代方案.本质上 ui-mask
指令没有做你想要的,所以你最好编写自己的指令.
I like the directive alternative. Essentially the ui-mask
directive isn't doing what you want, so you might as well write your own directive.
您不必将 inicio
传递给您的 view-value
指令.相反,将您自己的解析器添加到 ngModelCtrl.$parsers
.下面是一个例子:https://stackoverflow.com/a/15556249/215945
You shouldn't have to pass inicio
to your view-value
directive. Instead, add your own parser to ngModelCtrl.$parsers
. Here's an example: https://stackoverflow.com/a/15556249/215945
这篇关于如何在没有表单和指令的情况下从控制器内部访问 $ngModelController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!