1

In my form:

<div ng-controller="myCtrl" ng-init="init('<%=JSON.stringify(data)%>')">
    <input type="text" ng-model="Reg.email" />
</div>

In my angular controller

myApp.controller("myCtrl", ['$scope', '$http', '$parse', function($scope, $http, $parse) {
    $scope.init = function(myJsonData){
        if(myJsonData!=null)
        {
            var myData = angular.fromJson(myJsonData);
            $scope.Reg.email            = "test@example.com";
        }
    };
}]);

The above code will not initialize the values to the input field. But if i change model name by removing the Reg. the code will work fine.

ie. $scope.email is working and $scope.Reg.email not working in my case.

Please support !

ReNiSh AR
  • 2,782
  • 2
  • 30
  • 42

3 Answers3

1

What is the value of $scope.Reg?

JavaScript throws error when you try to access any property of undefined variable or property. Here $scope.Reg is not defined, you need to first set $scope.Reg={} if it is not defined. Then you can use Value of $scope.Reg and its properties in templates and JavaScript code as well.

Note: AngularJS don't throw any such error if you try to access property of undefined variable or property from angular templates.

In your case Reg property is not defined when init() gets called. Angular defines properties if it is not defined for any setter methods like ng-model.

myApp.controller("myCtrl", ['$scope', '$http', '$parse', function($scope, $http, $parse) {
    $scope.Reg=$scope.Reg||{}; // Define if not defined
    $scope.init = function(myJsonData){
        if(myJsonData!=null)
        {
            var myData = angular.fromJson(myJsonData);
            $scope.Reg.email            = "test@example.com";
        }
    };
}]);
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
1

The issue occured because you didn't define $scope.Reg object.

Define object like $scope.Reg = {};

Working plnkr Link

please check hope this is help you.

Manoj Salvi
  • 2,639
  • 1
  • 17
  • 21
Manoj Patidar
  • 1,171
  • 2
  • 11
  • 29
1

If $scope.Reg is undefined then first initialize it by $scope.Reg = {} then access properties of $scope.Reg

Mansi Parekh
  • 519
  • 2
  • 13