Dynamic form name attribute <input type=“text” name=“{{ variable-name }}” /> in Angularjs

后端 未结 4 1443
忘掉有多难
忘掉有多难 2020-11-29 08:07

How would someone use formName.inputName.$valid when the \"inputName\" was dynamically created?

  
4条回答
  •  被撕碎了的回忆
    2020-11-29 08:53

    Don't forget that you can access javascript objects using array notation with string indexes. Given the following arbitrary form definition object :

    $scope.form_def = {
      form_name : 'BallForm',
      variables : [
        height : { name : 'Height', type : 'text' },
        width : { name : 'Width', type : 'text' },
        color : { name : 'Color', type : 'multi', options : ['red', 'green', 'blue'] }
      ]
    };
    $scope.form_values = {};
    

    ... and the html snippet ...

    
      

    Inside the controller you then would have a nice form_values object for every field which you can access by iterating over the keys in the form_def.variables hash.

    There is a lot more involved once you get down into writing these sort of generic form processing scripts and you end up with a hell of a lot of spaghetti code in my opinion and you would probably be better of going with a less general solution, but thats another SO question.

提交回复
热议问题