$scope with dot (.) not initializing values to input fields in angular

会有一股神秘感。 提交于 2019-12-24 10:45:59

问题


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 !


回答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";
        }
    };
}]);



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/42388116/scope-with-dot-not-initializing-values-to-input-fields-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!