ngShow 和 ngHide
ng-show
指令根據傳遞給它的表示式是 true 還是 false 來顯示或隱藏 HTML 元素。如果表示式的值是假的,那麼它將隱藏。如果它是真的那麼它會顯示。
ng-hide
指令類似。但是,如果值為 falsy,則會顯示 HTML 元素。當表示式真實時,它會隱藏它。
控制器 :
var app = angular.module('app', []);
angular.module('app')
.controller('ExampleController', ExampleController);
function ExampleController() {
var vm = this;
//Binding the username to HTML element
vm.username = '';
//A taken username
vm.taken_username = 'StackOverflow';
}
檢視
<section ng-controller="ExampleController as main">
<p>Enter Password</p>
<input ng-model="main.username" type="text">
<hr>
<!-- Will always show as long as StackOverflow is not typed in -->
<!-- The expression is always true when it is not StackOverflow -->
<div style="color:green;" ng-show="main.username != main.taken_username">
Your username is free to use!
</div>
<!-- Will only show when StackOverflow is typed in -->
<!-- The expression value becomes falsy -->
<div style="color:red;" ng-hide="main.username != main.taken_username">
Your username is taken!
</div>
<p>Enter 'StackOverflow' in username field to show ngHide directive.</p>
</section>