ng-show无法使用<select> </select>

时间:2014-06-22 21:34:47

标签: javascript angularjs

我正在尝试隐藏或显示基于<select>数组引用的[]标记。 <select>标记由同一个数组支持。

<select ng-show="model.people" ng-model="model.selectedPerson" ng-options="person.name for person in model.people"></select>

然而它不起作用。 model.people最初为[]

当使用model.addPerson()添加第一个元素时,我希望model.people是真实的,因此将ng-show设置为真值并最终显示<select>标记。 / p>

javascript代码:

angular.module('app', [])
        .controller('FormController', function($scope) {
            var model={};
            model.person=function(person){
                return{
                        name:person.name,
                        age:person.age
                        };
            };
            model.people=[];
            model.addPerson=function(person){
                model.people.push(new model.person(person));
                if(model.people){
                    console.log(true);
                }else{
                    console.log(false);
                }
            };
            model.selectedPerson=model.people[0];
            $scope.model=model;
        });

HTML code:

<form name="form" ng-controller="FormController" ng-submit="model.addPerson(model.anyPerson)" novalidate>
    <input type="text" ng-model="model.anyPerson.name" ng-required="true" placeholder="Name"/><br/>
    <input type="number" name="age" ng-model="model.anyPerson.age" min="15" max="100" ng-required="true" placeholder="Age"/><br/>
    <button type="submit" ng-disabled="form.$invalid">Add Person</button><br/>
    <select ng-show="model.people" ng-model="model.selectedPerson" ng-options="person.name for person in model.people"></select><br/>
    <span ng-show="model.selectedPerson" ng-bind-template="Name: {{model.selectedPerson.name}}, Age: {{model.selectedPerson.age}}"></span>
</form>

1 个答案:

答案 0 :(得分:4)

空数组(一旦分配)成为一个对象。似乎这个对象总是 truthy(空或不)。

var empty = [];
if (empty) { 1; } else { 2; }

上面的代码,在我的测试中总是返回1

因此,我建议您在length > 0中使用ng-show代替:

<select ng-show="model.people.length > 0" ng-model="model.selectedPerson" ng-options="person.name for person in model.people"></select>