角 - 指令反映ngModel阵列 [英] Angular - Directive reflecting ngModel array
问题描述
这是背负有点过前面一个问题。我一直在试图从一个模型/阵列指令和数据的工作。
This is piggy-backing a little off an earlier question. I have been trying to work with directives and data from a model/array
我的模型看起来是这样的:
My model looks something like this:
$scope.testModel = {
inputA:[1,2,3]
};
然后我会在输入每一个。
Then I would have inputs for each.
我的指令检查,上KEYUP,如果输入电压低于一个给定的数目(10)的大。如果是,则它将其设置为10。
My directive is checking, on keyup, if the input is greater than a given number (10). If it is, then it sets it as 10.
link: function(scope, element) {
scope.$watch('ngModel',function(val){
element.val(scope.ngModel);
});
element.bind("keyup", function(event) {
if(parseInt(element.val())>10){
element.val(10);
scope.ngModel=element.val();
scope.$apply();
}
});
}
问题是,我得到一个错误,根据输入:
The problem is that I get an error, depending on the input:
类型错误:未定义无法设置属性0
TypeError: Cannot set property '0' of undefined
下面是小提琴看到错误和code我已经设置了:的http://的jsfiddle .NET / prXm3 / 3 /
Here is the fiddle to see the error and code I have set up: http://jsfiddle.net/prXm3/3/
注意
我想preFER不要因为我直接接收从服务器把数据集。我知道我可以改变模型 inputA0:1,inputA1:2,inputA2:3
,并得到它的工作,但我会在我的应用程序转换数据得到它,然后重新改造它,当我发送到回服务器。我想preFER离开模型,我已经将它设置。
I would prefer not to change the data set as I receive it directly from the server. I know I can change the model to inputA0:1,inputA1:2,inputA2:3
and get it to work, but then I would have to transform the data when my app gets it, and then re-transform it when I send to back to the server. I would prefer to leave the model as I have it set.
推荐答案
由于您的指令与 ngModel
互动,你应该与它一起工作,以同时更新模型和视图:
Since your directive is interacting with ngModel
, you should work along with it in order to update both the model and the view:
angular.module('test', []).directive('myDirective', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$parsers.unshift(function(viewValue) {
if(parseInt(viewValue) > 10) {
ngModel.$setViewValue(10);
ngModel.$render();
return 10;
}
else
return viewValue;
});
}
}
});
也许你有兴趣在检查出进一步的信息以下职位:
Perhaps you'd be interested in checking out the following posts for further information:
- NgModelController
- Developer's Guide on Forms
这篇关于角 - 指令反映ngModel阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!