加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS从指令中获取$event

发布时间:2020-12-17 07:28:56 所属栏目:安全 来源:网络整理
导读:看起来很简单,但我无法从我的指令中获取$event.当从cb-click调用test时,$event是未定义的,但在指令之外(通过html),它是事件对象. 如果我使用链接功能(不包括在我的小提琴中),我可以获得$event,但我无法在正确的范围内解析/ $eval它. http://jsfiddle.net/lan
看起来很简单,但我无法从我的指令中获取$event.当从cb-click调用test时,$event是未定义的,但在指令之外(通过html),它是事件对象.

如果我使用链接功能(不包括在我的小提琴中),我可以获得$event,但我无法在正确的范围内解析/ $eval它.

http://jsfiddle.net/langdonx/KgcGY/

<div ng-app="app" ng-controller="x">
    <!-- via directive -->
    <checkbox cb-model="y" cb-click="test($event,b)"></checkbox>
    <!-- via html -->
    <div><input id="c2" type="checkbox" ng-model="x" ng-click="test($event,'a')"> <label for="c2">{{x}}</label></div> 
</div>

var app = angular.module('app',[]);

app.directive('checkbox',function ($parse) {
    return {
        restrict: 'E',replace: true,scope: {
            cbModel: '=',cbClick: '&'
        },template: '<div><input id="c1" type="checkbox" ng-model="cbModel" ng-click="cbClick($event,'a')"> <label for="c1">{{cbModel}}</label></div>'
    };
});

app.controller('x',function x($scope) {
    $scope.x = true;
    $scope.y = true;
    $scope.test = function (ev,b) {
        console.log('test called,ev is',ev,'b is',b);
        return 'xyz';
    }
});
您需要在指令中使用此语法:
ng-click="cbClick({ev: $event,b:'a'})

使用此HTML:

cb-click="test(ev,b)"

Fiddle

从directives page开始,“指令定义对象”部分:

Often it’s desirable to pass data from the isolated scope via an expression and to the parent scope,this can be done by passing a map of local variable names and values into the expression wrapper fn. For example,if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读