AngularJS - call ng-submit with parameter

I am working with angular and passport to authenticate users; I'm trying to pass the registered user id when saving the form, but just can't seem to get it to 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 the console.log), although I can show it.

Any ideas?

thank

+3


source to share


1 answer


How is your form supposed to know what it is user

? The reason 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 function, the $scope.createSite()

value was user

not the same value as it was for the OUTSIDE function. The reason for this is that when a value is user

used as an argument in a function definition, trying to invoke that value - as you did in the statement console.log(user)

, you are essentially saying "console.log is the value that is being passed to this function." Please forgive me if you already know this, but in arguments JavaScript functions only act as references to values โ€‹โ€‹called by the function.

Here's a little JSfiddle to illustrate my point .

+3


source







All Articles