使用ng-if
加载它。所以基本上,如果你有一个范围变量假设$scope.showElement
那么你可以使用它像这样:
在你的控制器:
$scope.showElement = true;
HTML:
<this-directive ng-if="showElement"></this-directive>
最初的指令会出现,但当您更改$scope.showElement
的值时,它将被删除。
编辑根据您的评论:
设置你的$scope.showElement
为false和ng-click
其设置为true这样的:
angular.module('myApp', [])
.controller('testController', function($scope) {
$scope.showElement = false;
$scope.toggleElement = function() {
console.log('toggle element');
$scope.showElement = $scope.showElement ? false : true;
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
</head>
<body ng-controller="testController">
<button type="button" ng-click="toggleElement()">Show directive</button>
<div ng-if="showElement" style="width:100%;height:40px;background-color:red;">This element will be shown/removed</div>
</body>
</html>
编辑2:
如果您不介意元素仍然保留在页面上但是隐藏,您还可以使用css声明来获得更好的性能。使用CSS,它会是这样的:
angular.module('myApp', [])
.controller('testController', function($scope) {
$scope.showElement = false;
$scope.toggleElement = function() {
console.log('toggle element');
$scope.showElement = $scope.showElement ? false : true;
};
});
.hidden {
display: none;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
</head>
<body ng-controller="testController">
<button type="button" ng-click="toggleElement()">Show directive</button>
<div ng-class="{'hidden' : showElement === false}" style="width:100%;height:40px;background-color:red;">This element will be shown/removed</div>
</body>
</html>
我只是想加载和按钮注入指令单击。 –
如果可能,请告诉我如何使用ng-class加载指令。我使用ng-class来处理css类。 –
@MonojitSarkar不用NG,如果NG,如果是像$工作看它会在你的应用程序性能的影响 – byteC0de