0

I am experiencing some problems within the link function of my directive. I am starting a new timeout within mousedown event bound to the element, then clearing it on the mouseup. The timeout is not clearing and also other variables I call on the scope are not updating within the element.bind functions. When I log to console, both functions are being triggered but the $scope doesn't seem to update until after the timeout has completed?

How can I make this work? JS fiddle here: http://jsfiddle.net/xrh6dhf9/

HTML

<div ng-app="dr" ng-controller="testCtrl">
<holddelete param="myDeletedMessage" update-fn="doCallback(msg)"></test>    

JavaScript

var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
    $scope.myDeletedMessage = "Deleted Succesfully";
    $scope.doCallback = function(msg) {        
        alert(msg);
    }
});
app.directive('holddelete', ['$timeout', function( $timeout) {
    return {
        restrict: 'E',
        scope: {
            param: '=',
            updateFn: '&'
        },
        template: "<a href> <i class='fa fa-times fa-fw'></i>Delete  {{message}}</a>",
        replace: true,        
        link: function($scope, element, attrs) {  

            $scope.mytimeout = null;

           $scope.message = ">";

            element.bind('mousedown', function (e) {
                console.log("mousedown");
                $scope.message = "- Hold 2 Secs";
                $scope.mytimeout = $timeout(function(){ 
                    $scope.updateFn({msg: $scope.param});
                }, 2000)
            });
            element.bind('mouseup', function (e) {
                console.log("mouseup");
                $scope.mytimeout = null;

                $scope.message = ">";
            })
        }
    }
}]);

1 Answer 1

3

Instead of setting timeout as null use

$timeout.cancel($scope.mytimeout);

Also instead of setting event handlers using element.bind pass execute methods in scope with ng-mousedown and ng-mouseup

Fiddle: http://jsfiddle.net/xrh6dhf9/1/

Sign up to request clarification or add additional context in comments.

1 Comment

I have added a nice countdown to the hold to delete function here: jsfiddle.net/v98vuz3h

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.