【问题标题】:check param in object in ng-model在 ng-model 中检查对象中的参数
【发布时间】:2026-01-22 23:20:12
【问题描述】:

我有一些人的名单,如果此人有评论字段 - 您可以在 input:text 中编辑此信息。所以当人有这个字段时,我会显示这个字段。但是我有一个问题,当我删除以前的评论时 - 输入是隐藏的。是person.comment = "",我认为这听起来像是假的。

<input person="text" ng-show='person.comment' ng-model='person.comment'>

我尝试做这件事:

ng-show='person.comment || person.comment === ""'

但也许以不同的方式存在?喜欢comment in personMy plnkr.

【问题讨论】:

  • 如果我理解正确的话,看起来你的尝试确实解决了问题。在 plunker 中,如果我添加 ng-show='person.comment || person.comment === ""' 输入字段不会在删除输入字段中的文本时消失。
  • @Matthias 是的,但有时(不经常)person.comment - 未定义,所以我需要使ng-show='person.comment || person.comment === ""' || person.comment === undefined 这看起来很难看,所以也许我们有更好的检查方法。就像我们在 if if(comment in person) 中所做的一样
  • 在什么情况下你真正想隐藏输入字段?可以使用它,并在所有其他情况下显示它
  • @Matthias 我在 plnkr 中使用它,Jake 和 Jane 没有字段,因为他们在反对时没有参数注释
  • 或者更好的可能是person.hasOwnProperty('comment')

标签: angularjs


【解决方案1】:

要检查一个对象是否在 javascript 中有一个键,你可以这样写:

ng-show="person.hasOwnProperty('comment')"

来自How do I check if an object has a key in JavaScript?

【讨论】:

    【解决方案2】:

    在 $scope.stuff 数组上添加简单的 angular.forEach 循环,例如:-

    Js

    var app = angular.module('App', []);
    
    app.controller('Ctrl', function($scope) {
        $scope.hideVariable = true;
        $scope.stuff = [
          {
           name: 'Jack',
           age : 22,
           comment : 'good boy'
          },
          {
           name: 'Bob',
           age : 23,
           comment : 'likes beer'
          },
          {
           name: 'Alisa',
           age : 21,
           comment : 'pretty girl'
          },
          {
           name: 'Jane',
           age : 25,
           comment : "she's fine"
          },
          {
           name: 'Mike',
           age : 19,
           comment : 'playing guitar'
          }
        ]
       angular.forEach('$scope.stuff', function (data) {
          if(data.comment === null || data.comment === 'undefined' ) {
            $scope.hideVariable = false;
          }
       })
    })
    

    HTML

    <input person="text"ng-show="hideVariable" ng-model='person.comment'>
    

    通过这个plunker

    【讨论】:

    • 不,没有 ng-show 没有comment 的人也会有输入
    • 好的,然后只需在你的 Js 中添加 for 循环并传递一个布尔变量以使你的字段启用禁用,等待我会更新答案