当前位置: 动力学知识库 > 问答 > 编程问答 >

angularJS hide/show initially

问题描述:

Modified example works fine AFTER I've changed the input value

- initially hide/show does the exact opposite of what I want ? ( Hello "" )

Do I need to run some sort of 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>

网友答案:

you can use ng-init here

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

here is the Demo Plunker

OR use

<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

problem

yourName scope variable is undefined until your first change on that value. if you change the value once then there is a scope variable called yourName. you can see if you type and then backspace the textbox Who ARE you ? will print because at this point there is a variable called yourName.

you can initialize the variable using ng-init and then there is a variable called yourName in the scope. so yourName is not undefined.

as a second example !yourName, if yourName undefined or '' then !yourName become true.

网友答案:

That's because by default yourName is undefined. Try like this.

<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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: