Using angular and jquery, I applied the slideToggle function. To apply this function to only one specific HTML element, I use a single parameter function inside ng-click, my code works fine, but I want to know if there is another better way to implement ng-click directives and functions in angular:
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'); } }); }; });
One of my problems is how I communicate between the directive and the scope:
$scope.section = section;
and
if(attrs.toggle == scope.section){
I will be grateful for any recommendations for a better implementation of angular.
thanks
source share