angleとjqueryを使用して、slideToggle関数を実装しました。この関数を1つの特定のHTML要素にのみ適用するために、ng-click関数内で1つのパラメーターを使用しています。コードは正常に機能しますが、ディレクティブとng-click関数を角度で実装する別のより良い方法が存在するかどうかを知りたいです。
index.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>
styles.css
.div1 {
background: Brown;
width: 200px;
height: 200px;
text-align: center;
}
.div1 p {
position: relative;
top: 50%;
}
directives.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');
}
});
};
});
私自身の懸念の1つは、ディレクティブとスコープの間で通信する方法です。
$scope.section = section;
と
if(attrs.toggle == scope.section){
より良いAngularの実装のためのアドバイスをいただければ幸いです。
ありがとう