使用angular和jquery我实现了slideToggle函数.为了只将这个函数应用于一个特定的HTML元素,我在ng-click函数中使用了一个参数,我的代码工作正常,但是,我想知道是否存在另一个更好的方法来实现angular中的指令和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'); } }); }; });
我自己的一个问题是我在指令和范围之间进行沟通的方式:
$scope.section = section;
和
if(attrs.toggle == scope.section){
我将不胜感激任何更好的Angular实现的建议.
谢谢
Plunker演示:
http://plnkr.co/edit/u69puq?p=preview
原文链接:https://www.f2er.com/angularjs/143812.html仅供参考,在撰写本文时,AngularJS团队正在添加一个ngAnimate指令,该指令将(希望)提供jQuery目前提供的大部分动画功能,例如:滑动,褪色等,目前IMO严重失踪.
HTML
<div data-ng-controller="MainController"> <input type="button" value="Toggle First" ng-click="Box1=!Box1"> <input type="button" value="Toggle Second" ng-click="Box2=!Box2"> <input type="button" value="Toggle third" ng-click="Box3=!Box3"> <div class="div1" data-slide-toggle="Box1" data-slide-toggle-duration="100" > <p>This is section #1</p> </div> <div class="div2" data-slide-toggle="Box2" data-slide-toggle-duration="2000"> <p>This is another section #1</p> </div> <div class="div3" data-slide-toggle="Box3"> <p>This is 3 section #1</p> </div> </div>
JS
var myApp = angular.module("myApp",[]); myApp.controller('MainController',function($scope) { $scope.Box1 = $scope.Box2 = $scope.Box3 = true; }); myApp.directive('slideToggle',function() { return { restrict: 'A',scope:{ isOpen: "=slideToggle" },link: function(scope,element,attr) { var slideDuration = parseInt(attr.slideToggleDuration,10) || 200; scope.$watch('isOpen',function(newVal,oldVal){ if(newVal !== oldVal){ element.stop().slideToggle(slideDuration); } }); } }; });