javascript - I am trying to create a button that changes its icon and color when clicked in angularjs -
i using font awesome icons , want change button icon , color when clicked have written directive
directive('uitoggleclass', ['$timeout', '$document', function($timeout, $document) { return { restrict: 'ac', link: function(scope, el, attr) { el.on('click', function(e) { e.preventdefault(); var classes = attr.uitoggleclass.split(','), targets = (attr.target && attr.target.split(',')) || array(el), key = 0; angular.foreach(classes, function( _class ) { var target = targets[(targets.length && key)]; ( _class.indexof( '*' ) !== -1 ) && magic(_class, target); $( target ).toggleclass(_class); key ++; }); $(el).toggleclass('active'); function magic(_class, target){ var patt = new regexp( '\\s' + _class. replace( /\*/g, '[a-za-z0-9-_]+' ). split( ' ' ). join( '\\s|\\s' ) + '\\s', 'g' ); var cn = ' ' + $(target)[0].classname + ' '; while ( patt.test( cn ) ) { cn = cn.replace( patt, ' ' ); } $(target)[0].classname = $.trim( cn ); } }); } }; }]);
and index.html
<div class="jumbotron" ng-app="plunker"> <p> <button class="btn btn-default" ui-toggle-class="btn-success"> <i class="fa fa-cloud-upload text"></i> <span class="text">upload</span> <i class="fa fa-check text-active"></i> <span class="text-active">success</span> </button> </p> </div>
but not changing button when clicked can me? here fiddle
your fiddle has bunch of errors (you need set "no wrap - in <head>"
angular work.) also, have $
variable undefined
- did mean include jquery
? don't have to, simple example, , define as:
var $ = angular.element; // jqlite
here's working forked fiddle.
but don't need of this. can use built-in ng-class
directive:
<button class="btn btn-default" ng-class="{'btn-success': active}" ng-click="active = !active">toggle</button>
edit:
if need change contents of button, can re-use active
variable toggle displayed content:
<button class="btn btn-default" ng-class="{'btn-success': active}" ng-click="active = !active"> <i ng-hide="active" class="fa fa-cloud-upload text"></i> <span ng-hide="active" class="text">upload</span> <i ng-show="active" class="fa fa-check text-active"></i> <span ng-show="active" class="text-active">success</span> </button>
Comments
Post a Comment