angularJS最初隐藏/显示

时间:2015-02-23 08:54:03

标签: angularjs

修改后的示例在​​我更改输入值后工作正常 - 最初隐藏/显示与我想要的完全相反? (你好“”)
我是否需要运行某种on-ready-go()?

<!doctype html>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
</head>
<body>
    <div>
        <input type="text" ng-model="yourName" placeholder="Enter your name">
        <hr>
        <h1 ng-show="yourName == ''">Who ARE you ?</h1>
        <h1 ng-hide="yourName == ''">Hello "{{yourName}}"</h1>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您可以在这里使用ng-init

<input type="text" ng-model="yourName" placeholder="Enter your name" ng-init="yourName = ''">

这是Demo Plunker

使用

<div>
    <input type="text" ng-model="yourName" placeholder="Enter your name">
    <hr>
    <h1 ng-show="!yourName">Who ARE you ?</h1>
    <h1 ng-hide="!yourName">Hello "{{yourName}}"</h1>
</div>

Demo Plunker

<强>问题

yourName范围变量为undefined,直到您对该值进行第一次更改为止。如果您更改一次值,则会有一个名为yourName的范围变量。您可以查看是否键入然后退格文本框Who ARE you ?将打印,因为此时有一个名为yourName的变量。

您可以使用ng-init初始化变量,然后在范围中有一个名为yourName的变量。因此yourName不是undefined

作为第二个示例!yourName,如果yourName undefined'',则!yourName成为真。

答案 1 :(得分:0)

这是因为默认情况下yourNameundefined。试试这样。

<h1 ng-hide="yourName == '' || yourName == undefined ">Hello "{{yourName}}"</h1>

<!doctype html>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
</head>
<body>
    <div>
        <input type="text" ng-model="yourName" placeholder="Enter your name">
        <hr>
        <h1 ng-show="yourName == ''">Who ARE you ?</h1>
        <h1 ng-hide="yourName == ''|| yourName == undefined ">Hello "{{yourName}}"</h1>
    </div>
</body>
</html>