javascript - Angular 类型错误: Cannot read property 'icon' of undefined

标签 javascript angularjs

如何处理 Angular 上的空输入?

我想在后端验证而不是在前端验证。但是当我提交时,如果我让它在图标输入上为空,则会返回错误

 TypeError: Cannot read property 'icon' of undefined

这是我的表格:

 <div class="form-group">
                    <div class="form-material form-material-danger">
                        <input class="form-control" type="text" id="name" ng-model="menu.name" placeholder="Menu Name.." empty-to-null>
                        <label for="name">Name</label>
                    </div>
                </div>
                <div class="form-group">
                    <div class="form-material form-material-danger">
                        <input class="form-control" type="text" id="icon" ng-model="menu.icon" placeholder="Menu Icon.." >
                        <label for="icon">Icon</label>
                    </div>
                </div>

这是我的代码:

 var data = {
            icon: $scope.menu.icon,
            name: $scope.menu.name
        };

        AdminMenu.save(data, function (response) {
            console.log(response);
            $scope.menu = null;
            ResultService(response);
            $scope.dtInstance.reloadData();
        }, function (response) {
            ResultService(response.data);
        })
            .$promise.finally(function () {
                $scope.button_text = "Store";
                $scope.loading = false;
            });

最佳答案

$scope.menu = null

当您将menu设置为null时,Angular无法再找到menu.icon。如果您想“重置”它,您应该执行 $scope.menu = {}

当然,不要忘记在使用之前初始化 $scope.menu

关于javascript - Angular 类型错误: Cannot read property 'icon' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32944982/

相关文章:

javascript - 如何使用加减值验证文本框 angularjs

javascript - 使用 UI Router 进行分页时如何更改 URL?

javascript - ckeditor:如何删除其他特定标签内的标签

Javascript 鼠标悬停事件不起作用

javascript - 进度条寻找正确的目标元素

javascript - 使用 xlsx 库导入 excel 数据时出错

java - AngularJS 1.8.0 和 Jquery 3.6.0 兼容性问题

javascript - PHP 动态 CSS ... 在 Javascript 中?

javascript - 如何在 Angular 中设置属性的值?

javascript - 如何设置在 AngularJs 中最初选中的单选按钮?