i'm trying create reusable button directive has 'loading' state. is, when clicked disables , shows inline image denote loading, removes when complete. setting scope variable in click method , unsetting it, changes state of button.
i want method calls when clicked in parent scope, , want hook validation of parent scope, disables when parent form invalid. these parts i'm having difficulty getting work - know issues scope-related, i'm stuck.
<loading-button class="login" data-ng-click="login()" text="login" toggle="loaded"></loading-button>
i hoping below, how can bind click method declared on directive instance called directive? or, bad practice? doesn't work.
angular.module("app.directives").directive("loadingbutton", function () { return { restrict: "e", replace: true, transclude: true, template: '<button data-ng-click="{{ngclick}}">{{text}}<img class="loading" src="images/buttonloader.gif" alt=""></button>', scope: { "toggle": "=", "text": "=", "ng-disabled": "=", "disabled": "=", "ngclick": "&" }, link: function(scope, element, attributes) { scope.text = attributes.text; var expression = attributes.toggle; scope.$watch(expression, function(newvalue, oldvalue) { if(newvalue === oldvalue) { return; } if(newvalue) { element.removeattr("disabled"); element.find("img.loading").hide(); } else { element.attr("disabled", "disabled"); element.find("img.loading").show(); } }); } }; });
used in parent scope:
$scope.login = function () { $scope.loaded = false; // disable button , show loading // login stuff $scope.loaded = true; // enable button , hide loading }
edit:
here's fiddle
edit - simplest solution: if doing enabling button , hiding elements in button, don't need directive @ all:
<button ng-click="login()" ng-disabled="loading"><img ng-show="loading">login</button>
otherwise, if want in directive:
for starters, don't need {{}}
in click declaration in template, , need call ()
.
i changing attribute reference ngclick click - angular won't using names attributes:
<button data-ng-click="click()">
and use ng-show
, ng-disabled
button , image.
<button ng-click="click()" ng-disabled="text==\'loading\'"> <img ng-show="text==\'loading\'">{{text}}</button>
.
for text
attribute, since reading value of string, want change scope setting text: "@"
.
also, since toggle
being set in isolate scope, can $watch
directly changes.
*note example of disabling , showing elements based on scope $watch
. disabling , showing may need exact opposite values of ones below, or may dependent on different scope variable:
scope.$watch('toggle', function(newvalue, oldvalue) { if(newvalue === oldvalue) { return; } if(newvalue) { scope.text = "loaded"; ; } else { scope.text="loading"; } });
.
this fiddle reflects working example based on setup, simulated loading time using $timeout
.
Comments
Post a Comment