Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Calling ng-submit with a parameter

I'm working with angular and passport for user authentication; I'm trying to pass the logged-in user ID when saving a form but just can't manage to make it work. My code is pretty simple:

site.jade:

div(ng-controller='sitesController')
    h1 #{user.local.email}
    form.(ng-submit="createSite(user)")
        label Site Name
        input.(type="text" ng-model="siteName")
        button.btn.btn-primary(type="submit") Save


sitesController.js

$scope.createSite = function (user) {
        console.log(user); // user = undefined
}

The user is always 'undefined' (in console.log), even though I'm able to show the email.

Any ideas?

Thanks

like image 357
Lior Ohana Avatar asked Jan 20 '26 11:01

Lior Ohana


1 Answers

How is your form supposed to know what user is? The reason why it is undefined is because you haven't defined it. Why not just do it this way?

site.jade:

div(ng-controller='sitesController')
    h1 #{user.local.email}
    form.(ng-submit="createSite()")
          //removed the argument from above.
        label Site Name
        input.(type="text" ng-model="siteName")
        button.btn.btn-primary(type="submit") Save


sitesController.js

$scope.createSite = function () {
        console.log($scope.siteName);
}

In your $scope.createSite() function, the value user was NOT the same value as it would have been OUTSIDE of the function. The reason for this is that when the value of user is used as an argument in a function definition, trying to call that value -- like you did in your console.log(user) statement -- you are essentially saying "console.log the value that is passed into this function." Please pardon me if you already know this, but in JavaScript function arguments only act as references to the values the function gets called with.

Here is a little JSfiddle to illustrate my point.

like image 176
Pytth Avatar answered Jan 22 '26 01:01

Pytth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!