问题
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