dede
dede

Reputation: 841

How to get value of ng-Model into Controller angular js

Please help me to check this part of code.

<body ng-app = "myApp">
<h1>FORM </h1>
    <div ng-controller="myController">
    <p><label>Username : </label><input type="text" ng-model="user.username" name="username" id="username" /></p>
    <p><label>Email : </label><input type="email" ng-model="user.email"/></p>
    <p><label>Verifikasi Email : </label><input type="email" ng-model="user.verify_email"  /></p>
    <p><label>Password : </label><input type="password"  ng-model="user.password" id="password" /></p>
    <button type="button" ng-click = "add()"  >Sig In</button>
</div>
</body>

In my Javascript:

<script>
var app = angular.module('myApp', []);
    app.controller("myController", function($scope){
$scope.user = {};
$scope.add = function(){
     $scope.data = [
                    { nama : $scope.user.username},
                    { email : $scope.user.email},
                    {password : $scope.user.password } ];
console.log($scope.data);
    }               
 });

Thanks for you all. I already update my script. When I click the button, the console didn't print the data. Why? I think there is something wrong.

Upvotes: 6

Views: 28199

Answers (2)

M. Hanafi
M. Hanafi

Reputation: 66

in your HTML you should

<body ng-app = "myApp"> 

    <div ng-controller="myController">
        <p><label>Username : </label><input type="text" ng-model="user.username" name="username" id="username" /></p>
        <p><label>Email : </label><input type="email" ng-model="user.email"/></p>
        <p><label>Verifikasi Email : </label><input type="email" ng-model="user.verify_email"  /></p>
        <p><label>Password : </label><input type="password"  ng-model="user.password" id="password" /></p>
        <button type="button" ng-click = "add(user)"  >Sig In</button> 
    </div> 

</body>

in case of

ng-click = "add()"

use

ng-click = "add(user)"

in your controller

$scope.add = function(user){

    $scope.data = [
        { name : user.username},
        { email : user.email},
        {password : user.password } 
    ];

    console.log($scope.data);

}); // End add Function

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You didn't define user

But that shouldn't be the problem if you use only user as model like

<input type="text" ng-model="user" name="username" id="username" />

It'll be added as property in the scope without any worries.

But you have added property username in user.

As user is undefined so the scenario will be undefined.username which is not permitted.

Try to defined user as object then any property will automically added.

Like this

$scope.user={};

Upvotes: 7

Related Questions