简体   繁体   中英

AngularJS controllers object is undefined

In the following code, when the data is saved, the console.log(user) is returning undefined . What is wrong here?

<input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="user.name">
<a class="btn btn-link pull-right" ng-click="save(user)">Save</a> 

Controllers:

LControllers.controller( 'InstanceCtrl', ['$scope', 'Instance', 'User',
function ($scope, Instance , User) {
    $scope.user= '';
    $scope.save = function (user) {
        console.log(user)// undefined
        console.log(user.name)       
    };

JSFiddle: http://jsfiddle.net/U3pVM/15248/

For me , it seems fine

http://jsfiddle.net/U3pVM/15248/ JSFiddle

after your fill some value in input box, code works fine. First time user is an empty string and hence user.name would be undefined.

And yes the right way to declare an object is

$scope.name = {};

not

$scope.name="";

I wired up a quick jsFiddle and it seems fine: http://jsfiddle.net/tfqytchk/

Of course the first time you press save user is an emptry string and user.name is undefined (I think that's what you're reporting). If you want that to change that behavior then change $scope.user = ''; to $scope.user = { name: '' };

Do not declare object like this

      $scope.user= '';

Declare object like

      $scope.user= {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM