带点 (.) 的 $scope 不初始化值以角度输入字段 [英] $scope with dot (.) not initializing values to input fields in angular

查看:34
本文介绍了带点 (.) 的 $scope 不初始化值以角度输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以我的形式:

<input type="text" ng-model="Reg.email"/>

在我的角度控制器中

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

上面的代码不会初始化输入字段的值.但是,如果我通过删除 Reg. 来更改模型名称,代码将正常工作.

即.$scope.email 正在工作,而 $scope.Reg.email 在我的情况下不起作用.

请支持!

解决方案

$scope.Reg 的值是什么?

当您尝试访问未定义变量或属性的任何属性时,JavaScript 会抛出错误.这里$scope.Reg没有定义,如果没有定义,需要先设置$scope.Reg={}.然后您也可以在模板和 JavaScript 代码中使用 $scope.Reg 的值及其属性.

<块引用>

注意:如果您尝试从 Angular 模板访问未定义变量的属性或属性,AngularJS 不会抛出任何此类错误.

在您的情况下,调用 init() 时未定义 Reg 属性.如果没有为 ng-model 等任何 setter 方法定义属性,Angular 会定义它.

myApp.controller("myCtrl", ['$scope', '$http', '$parse', function($scope, $http, $parse) {$scope.Reg=$scope.Reg||{};//如果没有定义就定义$scope.init = 函数(myJsonData){if(myJsonData!=null){var myData = angular.fromJson(myJsonData);$scope.Reg.email = "test@example.com";}};}]);

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 !

解决方案

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

这篇关于带点 (.) 的 $scope 不初始化值以角度输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆