javascript 类型错误:无法设置未定义的属性“”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32257374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:02:34  来源:igfitidea点击:

TypeError: Cannot set property '' of undefined

javascriptangularjs

提问by Nics1225

For some reason, I can't seem to bring this variable into scope to be manipulated.

出于某种原因,我似乎无法将此变量带入要操作的范围。

Markup:

标记:

<label>Description only <input ng-model="filter.Description"></label><br>
<label>Tags only <input ng-model="filter.Tags.Text"></label><br> //This methodology works

<div ng-repeat="t in filteredTags" style="display:inline-block">
    <button class="btn btn-warning" ng-click="FilterByTag(t.Text)">
        {{t.Text}}
    </button>
</div> //But I want these buttons to work for the same thing, and they don't

.....

.....

<tr ng-repeat="b in filteredBookmarks| filter: filter:strict">

JavaScript:

JavaScript:

 $scope.FilterByTag = function (tagName) {
        filter.Tags.Text = tagName;
    };

If I change the JS variable to $scope.filter.Tags.Text = tagName;I get an error that reads: TypeError: Cannot set property 'Text' of undefined. Has anybody run into something similar?

如果我改变了JS变量,$scope.filter.Tags.Text = tagName;我得到一条错误:TypeError: Cannot set property 'Text' of undefined。有没有人遇到过类似的事情?

回答by machinehead115

Try initializing your filter object first:

首先尝试初始化您的过滤器对象:

$scope.filter = {
    'Tags': {
        'Text': null
    },
    'Description': null
}

回答by WebWanderer

Your function should read:

你的函数应该是:

$scope.FilterByTag = function (tagName) {
    $scope.filter.Tags.Text = tagName;
};

Your filterobject is on the $scope

你的filter对象在$scope

回答by Mahaveer Jain

Of course it is because the hierarchy you are specifying for setting your tagName is not present. so it find the Tags itself is undefined and you are trying to set the Text value of it which is undefined and you got the error.

当然,这是因为您指定用于设置 tagName 的层次结构不存在。所以它发现标签本身是未定义的,你试图设置它的未定义的文本值,你得到了错误。

Try to specify a default data structure of your object where you want to store the value.

尝试指定要存储值的对象的默认数据结构。

$scope.filter = {
  'Tags': {
      'Text': undefined
  },
  'Description': undefined
}