使用 angular 和 jquery 我实现了 slideToggle 功能。为了仅将此函数应用于一个特定的 HTML 元素,我在 ng-click 函数中使用了一个参数,我的代码工作正常,但是,我想知道是否存在另一种更好的方法来实现指令和 ng-click 函数的角度:
索引.html
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="MainController">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="css/styles.css"/>
</head>
<body>
<div>
<input type="button" ng-click="toggle('first')" value="Toggle First">
<input type="button" ng-click="toggle('second')" value="Toggle Second">
<input type="button" ng-click="toggle('third')" value="Toggle third">
<div class="div1" section="first" toggle="first" >
<p>This is section #1</p>
</div>
<div class="div1" toggle="second">
<p>This is another section #1</p>
</div>
<div class="div1" toggle="third">
<p>This is 3 section #1</p>
</div>
</div>
</body>
<footer>
<script src="js/jquery.min.js"></script>
<script src="js/angular.js"></script>
<script src="js/directives.js"></script>
</footer>
</html>
样式.css
.div1 {
background: Brown;
width: 200px;
height: 200px;
text-align: center;
}
.div1 p {
position: relative;
top: 50%;
}
指令.js
angular.module("myApp", []) //
.controller('MainController', function($scope) {
$scope.toggle = function(section) {
console.log('<toggle function> section :' + section);
$scope.section = section;
$scope.$broadcast('event:toggle');
}
}) //
.directive('toggle', function() {
return function(scope, elem, attrs) {
scope.$on('event:toggle', function() {
if(attrs.toggle == scope.section){
elem.slideToggle('fast');
}
});
};
});
我自己关心的一个问题是我在指令和范围之间进行通信的方式:
$scope.section = section;
和
if(attrs.toggle == scope.section){
对于更好的 Angular 实现,我将不胜感激。
谢谢