TypeError: Cannot set property '' of undefined

时间:2015-08-27 18:55:53

标签: javascript angularjs

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:

 $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?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

您的功能应为:

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

您的filter对象位于$scope

答案 2 :(得分:0)

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

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

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