简体   繁体   中英

Angularjs - Loading JSON data with $scope values (dynamic) returns undefined

I have ng-model to my input field like below.

<div ng-app="myApp" ng-controller="GlobalCtrl">
    <input type="text" ng-model="FirstName">
        {{FirstName}}
</div>

Now in my controller console.log $scope.FirstName is the correct values I give in my view.

But when I try to load the $scope into a JSON like structure I get undefined.

myApp.controller('GlobalCtrl', function($scope) {

    $scope.loadedata = {"asd":$scope.FirstName};
    console.log($scope.FirstName); //this is fine
    console.log($scope.loadedata); //but this is undefined.
});

Now $scope.loadedata) is undefined . why is it? what am I doing wrong?

There are a few things about your code snippet. You are using an input bar where your DOM is trying to render FirstName which is undefined. See this demo for the proper us of the input and two-way binding template-controller relationship.

https://material.angularjs.org/latest/demo/input

Also, where are you calling the console.log()? I assume after the controller call?

My view:

<div ng-app="myApp" ng-controller="GlobalCtrl">
<input type="text" ng-model="req.FirstName">
    {{req.FirstName}}
</div>

My Controller :

myApp.controller('GlobalCtrl', function($scope) {
$scope.req = {};
console.log(JSON.stringify($scope.req));
});

After a long research, I found out that it's better to do without serializing and you can do like this using ng-model. And it works.

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