📜 ⬆️ ⬇️

Forms in Angularjs. How I found love

I had to do it again. It would seem nothing terrible, I did it hundreds of times. But the feeling ... the feeling that everything is wrong, should not be and there should be another way out, did not leave me. Then I did not know that soon I would have a meeting that would change my world forever, open my eyes and fill life with meaning. The meaning of getting up every morning, the meaning of doing something that has practically ceased to give me pleasure, the meaning of sharing this feeling with others.


River flows...


This story originates in the distant 1992, when the first version of the holy scripture was published, most of the precepts of which determined the course of human development for many years to come. The attentive reader will surely note that in this manuscript there is no mention of several very important canons, without which today there is not a single scholar.

Among them is one of the main characters of my story. The naked eye can see that HTML primordial, like a diamond that has not been cut, was formless. Naturally, this could not continue for a long time, and already on November 8, 1993, the first features of the new form appeared from the depths of the jewelry workshop to the world, which subsequently received their rightful place on the tables of the second coming .
')
And it would seem that peace has come to the world. Now ordinary people could not only receive information, but also respond. And if heresy is found in their words, the mysterious guard from Backend will always come to the rescue and guide them on the right path with their righteous speeches. But calm has no place in this drama.

The whole history of humanity is the path to freedom. Freedom from slavery, from the yoke of kings, from the borders of their native lands. It is enough that for a thousand people living in humility, there is one free-thinker, and here again the ships are sailing, barricades are erected, negros are running for president. So it was this time, people wanted freedom, freedom from the bonds of the server part. Freedom, which promised them the divine power of interfaces, savings on data transfer, the road to the golden city of Frontend.

Come to the point


But back to the main story line. What happened to the form? The form began to change. With the development of the Frontend from such a pagan portal into the world of wandering life, it became an element of its decoration, transferring its power into the hands of the Church of Javascript. Why this happened, only Morgan Freeman is aware, we look at the facts. But the facts are such that only the Old Believers, and the Jesuits, who spat on the human desire for perfection in the context of customer ignorance, continued to check the form on the server part.

Your humble servant has never attributed himself to either one or the other. Young rage, I lived and enjoyed life. Need validation? Yes, please, jQuery validation , but at least I'll write it myself. Time after time the same thing: email, password, name ... email, password, name ... email, password, date ... And now, like a top in a safe, a thought originated in my head that twisted and turned endlessly. Now that I had the task to write the form processing, I was overcome by the feeling that I was an Indonesian peasant who was forced by a mop to clean the snow from the windshield of his moped for lack of janitors who, according to common sense, had to be installed at the factory.

And here, of course, as a decent parishioner of the church of the Holy Trinity , my joy knew no bounds when the miraculous attributes of the fifth reincarnation were revealed to us. Once again they gave me hope and faith that there, on the other side of the cable, there is someone and he hears my pleas. But, to admit, the euphoria was short. The absence of the possibility of stylization, control over the status of filling in the form still required that each time the logic that controls the presentation was recorded.

But once, in a circle of their sectarian friends, they brought me to a beautiful maiden. She was young and just started to appear. Called her, if the Russian style, Angela . At first she seemed strange to me. Most of all, I was embarrassed by the fact that she did not try to hide anything, but everything was head-on. It was wild for my upbringing . I don’t know if she attracted me with her manners or, perhaps, I was influenced by the fact that I admired her father , a serious authority in our circles. But I wanted to know Angela better, because as a girl she was available .

Well, well, do not pull


I will not go into all the details of our relationship, especially since I was not the first to have her . Angela's language was capable of such incredible things that I wanted to learn it deeper and deeper. But as I remember the day when I finally lost my head. On this day, she first showed me the form.

Have waited


In general, it was indescribable. She, as if reading my thoughts, did everything that I could wish for. Want to set styles for pristine input and no? Ask, she swallow.

.ng-pristine{ /* */ } .ng-dirty{ /* */ } 

It remains only to write the code that will apply these styles. Here he is:

[ jsFiddle ]
 <input type="text" ng-model="example"> 


If someone already got up
The question is what about valid-invalid:

[ jsFiddle ]
 .ng-valid{ /* */ } .ng-invalid{ /* */ } 

 <input type="email" ng-model="example"> 


In general, guys, dabbled. Started her courting. And then she, I must say, revealed to the full. I realized that the task of styles was just fun for a first date. In fact, she could not have dreamed of others. Make a validation interface with custom messages without a single javascript line? Made by:

[ jsFiddle ]
 <form name="LovelyForm"> <input type="email" name="LovelyEmail" ng-model="email"/> <span ng-show="LovelyForm.LovelyEmail.$invalid">You break my heart</span> </form> 

And here is a complete analogy with styles, that is, logical properties are defined in the LovelyForm.LovelyEmail object that correspond to the styles given earlier:

 (boolean) LovelyForm.LovelyEmail.$invalid; (boolean) LovelyForm.LovelyEmail.$valid; (boolean) LovelyForm.LovelyEmail.$dirty; (boolean) LovelyForm.LovelyEmail.$pristine; 

The juice is that Angular out of the box contains directives that duplicate the attributes of the HTML5 form validation.

[ jsFiddle ]
 <form name="LovelyForm"> <input type="number" name="LovelyNumber" ng-model="number" min="0" max="10" required/> <span ng-show="LovelyForm.LovelyNumber.$error.required">Show me your number</span> <span ng-show="LovelyForm.LovelyNumber.$error.min">OMG, so min</span> <span ng-show="LovelyForm.LovelyNumber.$error.max">OMG, too max</span> <input type="text" name="LovelyLove" placeholder="I Love U" ng-model="love" ng-pattern="/I love U too/" required /> <span ng-show="LovelyForm.LovelyLove.$error.pattern">What?! Fucking buster!</span> </form> 

Personally, I was delighted, because it was just such minimal flexibility in singing that the notorious HTML5 lacked.

Own validator


But the most important thing is how easily Angela is ready to accept the validator that you created on the side into her womb. For this, all you need to do is write the appropriate directive:

[ jsFiddle ]
 app.directive('mimimi', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(mimimi) { if (/mimimi/.test(mimimi)) { alert('mimimi'); ctrl.$setValidity('mimimi', true); return mimimi.toUpperCase(); } else { ctrl.$setValidity('mimimi', false); return undefined; } }); } }; }); 

 <form name="LovelyForm"> <input type="text" name="LovelyMimimi" placeholder="mimimi" ng-model="mimimi" mimimi/> <span ng-show="LovelyForm.LovelyMimimi.$error.mimimi">Mimimi, please</span> <span>{{mimimi}}</span> </form> 

It often seems to me that the developers of Angular sought to create such a framework, the code of which would cause the same feelings among people who are familiar with programming or not. Therefore, I will explain a little about what is happening all the more since its essence is quite simple.

When using the ngModel Angular directive, it creates an instance of a special NgModelController controller, which in general is responsible for all these validation properties: $ invalid, $ valid, $ pristine, $ dirty, $ error. Therefore, when writing a validator, we need to use a controller that belongs to ngModel, which we do:

 require: "ngModel"

Now the link function, which is called upon any changes, will take the NgModelController controller as the ctl parameter.

Next we turn to the $ parsers array of the NgModelController object, which sequentially performs the specified functions, passing the contents of the input to them.

Perform a regular expression check. And if everything is ok, declare LovelyForm.LovelyMimimi. $ Error.mimimi as valid ctrl. $ SetValidity ('mimimi', true). The value returned by the function will be passed to the parent $ scope, in our case, to the mimimi variable.

Submitsim


Finally, we want to process the data that the user has kindly provided to us. With Angular, this is also done on time:

[ jsFiddle ]
 <form name="LovelyForm" novalidate ng-controller="formController" ng-submit="submit()" > <input type="text" name="LovelyText" placeholder="Some Text 1" ng-model="text1" required/> <input type="text" name="LovelyText2" placeholder="Some Text 2" ng-model="text2" required/> <input type="text" name="LovelyText3" placeholder="Some Text 3" ng-model="text3" required/> <input type="submit" value="Send Text" ng-disabled="LovelyForm.$invalid"> </form> 

 function formController($scope){ $scope.submit=function(){ alert(angular.toJson($scope.LovelyForm)); } } 

In essence, one of the two ngSubmit or ngClick directives is enough. The only difference is that the first one you specify in the form tag, the second to input with the attribute type = "submit". In this case, the specified function will be executed, both when clicking on the button, and when you press Enter after entering in one of the fields.

Of course, in order to prevent the emergence of native HTML5 validation messages, it is advisable to assign the novalidate attribute to the form. And in order to make the submit or click action impossible when the form is filled with errors, we use the ngDisabled directive. If ngDisabled is true, then submit will not pass.

Married


In general, what is it I, men. Be careful. I lived my life, changed the plug-ins for jQuery like gloves. But once I relaxed, I stuck my nose, but I did not pull it out in time. Now we’ll have our children with Angelica soon, one-page, so I can't even look at jQuery now. But I think I'm not the only one here. Thank you for listening.

Source: https://habr.com/ru/post/179473/


All Articles