scope-username
scope-username

Reputation: 75

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?

Upvotes: 1

Views: 39

Answers (2)

scope-username
scope-username

Reputation: 75

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.

Upvotes: 1

Michael Walker
Michael Walker

Reputation: 91

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?

Upvotes: 1

Related Questions