从指令的link函数中的element.bind中访问范围

时间:2015-03-29 21:29:55

标签: angularjs angularjs-directive angularjs-scope

我在指令的link函数中遇到了一些问题。我在绑定到元素的mousedown事件中开始新的超时,然后在mouseup上清除它。超时未清除,并且我在作用域上调用的其他变量也未在element.bind函数中更新。当我登录到控制台时,两个函数都被触发但是$ scope在超时完成之前似乎没有更新?

我该如何使这项工作? JS在这里小提琴: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 个答案:

答案 0 :(得分:3)

而不是将超时设置为null使用

$timeout.cancel($scope.mytimeout);

而不是使用element.bind设置事件处理程序而不是使用ng-mousedownng-mouseup

传递范围内的执行方法

小提琴:http://jsfiddle.net/xrh6dhf9/1/