Angular ng-click event delegation

后端 未结 4 1519
猫巷女王i
猫巷女王i 2020-12-02 14:34

So if i have a ul with 100 li\'s should there be ng-clicks in each li or is there a way to bind the event to the ul and delegate it to the li\'s kind of what jquery does? Wo

4条回答
  •  时光说笑
    2020-12-02 15:08

    Starting from BradGreens' delegateClicks above, I've adapted some code from georg which allows me to place the handleMenu function deeper in $scope (e.g. $scope.tomato.handleMenu).

    app.directive('delegateClicks', function () {
        return function ($scope, element, attrs) {
            var fn = attrs.delegateClicks.split('.').reduce(function ($scope, p) { return $scope[p] }, $scope); 
            element.on('click', attrs.delegateSelector, function (e) {
                var data = angular.fromJson(angular.element(e.target).data('ngJson') || undefined);
                if (typeof fn == "function") fn(e, data);
            });
        };
    });
    

提交回复
热议问题