Angular - Directive reflecting ngModel array

Deadly 提交于 2019-12-08 10:17:24

问题


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.

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:

TypeError: Cannot set property '0' of undefined

Here is the fiddle to see the error and code I have set up: http://jsfiddle.net/prXm3/3/

NOTE

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.


回答1:


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;
          });          
      }
  }
});

Working jsFiddle.

Perhaps you'd be interested in checking out the following posts for further information:

  • NgModelController
  • Developer's Guide on Forms


来源:https://stackoverflow.com/questions/18747573/angular-directive-reflecting-ngmodel-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!