概述
在Angular JS中,可以使用ng-if指令來控制元素是否存在。
實現(xiàn)細(xì)節(jié)
ng-if標(biāo)簽通過監(jiān)控綁定的數(shù)據(jù),在數(shù)據(jù)發(fā)生變化時,如果為true就存在,為false就不存在。
//顯示
$animate.enter(clone, $element.parent(), $element);
//影藏
$animate.leave(previousElements).then(function() {
previousElements = null;
});
從代碼可以看出,在元素添加和刪除是動過$animate完成的,這說明添加和刪除的過程可以動畫實現(xiàn)。
另外:ng-if不僅僅可以綁定數(shù)據(jù)模型,還可以綁定表達(dá)式。ng-if具有高優(yōu)先級(600),同時還具有terminal屬性為true,所以在具有ng-if指令的元素上,很多其它指令是無效的。
示例代碼
<!DOCTYPE html>
<html lang="en" ng-app="app">
<!--<html>-->
<head>
<title>Test</title>
</head>
<body ng-controller="testCtrl">
<div>
<input type="button" value="click" ng-click="test()">
</div>
<div>
<div ng-if ="data" >test1</div>
<div ng-if ="data >3" >test2</div>
</div>
</body>
<script src="./node_modules/angular/angular.js" type="text/javascript"></script>
<script>
angular.module("app",[]).controller("testCtrl",["$scope",function($scope){
$scope.data = 0;
$scope.test = function(){
$scope.data += 1;
if($scope.data > 5){
$scope.data = 0;
}
}
}]);
</script>
</html>
這段代碼實現(xiàn)的功能為:當(dāng)點擊按鈕,$scope的data值就會自增1,當(dāng)data大于5時就會還原為0。test1在data不為0時就顯示,test2在data大于3時顯示。