Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular get form elements

I am trying to get element name and class from a form that is passed on to a function. How can i do that?

Html side.

   <form name="test">
    <div>
         <input type="text" class="test1" name="test2"/>
    </div>
    <div>
         <input type="text" class="test3" name="test4"/>
    </div>
    </form>
    <div>
         <input type="button" data-ng-click="save(test)" />
    </div>

and Javascript side

$scope.save = function(form){
   for(how many elements are there)
       (get elements values)
}

how can I do that, can it even be done like that? My purpose is to change class and some other attributes when it's necessary.

like image 744
Kapaacius Avatar asked Dec 12 '22 13:12

Kapaacius


2 Answers

You can access the form directly from $scope using its name, i.e. $scope.test, and the elements from the form, e.g. $scope.test.test2.

However, if you want to loop through the elements without having to know their individual names you can do something like:

angular.forEach($scope.test, function (element, name) {
    if (!name.startsWith('$')) {
        // element is a form element!
    }
});
like image 168
Mark Rhodes Avatar answered Dec 26 '22 14:12

Mark Rhodes


I'm relatively new to AngularJS, but I am going to make a solid attempt to answer to test my knowledge and hopefully help you.

So in your form, on each of your elements you should use a ng-model. For example, here is a form that may collect a users first and last name:

 <form name="test">
<div>
     <input type="text" class="test1" name="test2" data-ng-model="user.name/>
</div>
<div>
     <input type="text" class="test3" name="test4" data-ng-model="user.last/>
</div>
</form>
<div>
     <input type="button" data-ng-click="save(test)" />
</div>

This will allow you to access the data in your form through $scope.user.

Now for changing classes and attributes, I'm not sure what rules dictate a class/attribute change on your form, but you could use the ng-dirty class as a "flag" to watch for when the user makes a change. Some more information here as to what exactly you are trying to accomplish would be helpful.

like image 28
Anthony Avatar answered Dec 26 '22 16:12

Anthony