Angular form submit function question

23 views
Skip to first unread message

Bennie Copeland

unread,
Sep 10, 2015, 12:05:56 AM9/10/15
to AngularJS
I recall either reading a blog entry or watching a video where it was recommended to pass the form data into the controllers submit function instead of tying it directly to the controllers scope. I see it being done by Matias in Taming Forms in AngularJS 1.3 where his form submit function looks like:

    ngModule.controller('FormCtrl', function($http) {
     
this.submit = function(isValid, data) {
       
if(!isValid) return;
   
       
//submit the data to the server
        $http
.post('/api/submit', data);
     
}
   
});

I know I have either read or watched something where it explained the reasoning behind it, but I can't recall where or find it in my favorites. I'm hoping somebody recalls this too and can point me in the right direction.

Sander Elias

unread,
Sep 10, 2015, 1:14:27 AM9/10/15
to AngularJS
Hi Bennie,

Passing the data into a function, using parameters, in stead of relying on some way off communication (in an angular app usually $scope), makes it way more explicit. Being explicit makes later on refactoring/maintenance much easier.
Imagine that you need to move the actual function that does the submit to another controller/service/directive/whatever. If that function is using scope, that's more of a challenge. If it receives everything it needs trough its parameters, it is much easier to do this right?
Testing also becomes simpler for this function. No more fussing around with $scope. Just feed it an object with test-data  and check if it's getting saved.

I'm not aware of the blog/video you are referring to, so I can't help you with that. Just hoping that this answer is somewhat usefull to you?

Regards
Sander

Reply all
Reply to author
Forward
0 new messages