gpt4 book ai didi

javascript - 从 ng-repeat oddity 内部的 ng-click 访问事件对象

转载 作者:行者123 更新时间:2023-11-30 00:10:39 24 4
gpt4 key购买 nike

http://jsfiddle.net/5mbdgau1/3/

在我的 fiddle 示例中,我访问了通过 ng-click 传入的事件对象。它工作正常,虽然在处理来自“OtherService”的 promise 时访问它时它突然不存在了?这是怎么回事?

使用 jQuery 是可行的,所以我认为这与 Angular jQlite 有关。此外,它会在 ng-repeat 内部中断,否则它会起作用。我想知道为什么事件对象似乎消失了。谢谢。

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

myApp.controller('TestController', function(TestService) {
var vm = this;

vm.foo = TestService;
vm.items = [1, 2, 3, 4];
});

myApp.service('OtherService', function($http) {
return $http.get('https://httpbin.org/get').then(function() {});
});

myApp.service('TestService', function(OtherService) {
return function(evt) {
var myText = evt.currentTarget.textContent;
evt.currentTarget.textContent = "Bar";
OtherService.then(function() {
console.log(evt);
evt.currentTarget.textContent = myText + myText;
});
}
});

html:

<div ng-controller="TestController as vm">
<div ng-repeat="item in vm.items">
<div ng-click="vm.foo(item, $event)">{{item}}</div>
</div>
</div>

最佳答案

您以错误的顺序从 ng-click 传递参数。从

更改 ng-click
<div ng-click="vm.foo(item, $event)">{{item}}</div>

<div ng-click="vm.foo($event, item)">{{item}}</div>

您的 TestService 函数首先需要一个事件对象。

// Code goes here
var myApp = angular.module('myApp',[]);

myApp.controller('TestController', function(TestService) {
var vm = this;

vm.foo = TestService;
vm.items = [1, 2, 3, 4];
});

myApp.service('OtherService', function($http) {
return $http.get('https://httpbin.org/get').then(function() {});
});

myApp.service('TestService', function(OtherService) {
return function(item, evt) {
console.log(evt, item)
var myText = evt.currentTarget.textContent;
evt.currentTarget.textContent = "Bar";
OtherService.then(function() {
console.log(evt);
evt.currentTarget.textContent = myText + myText;
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="TestController as vm">
<div ng-repeat="item in vm.items">
<div ng-click="vm.foo(item, $event)">{{item}}</div>
</div>
</div>

关于javascript - 从 ng-repeat oddity 内部的 ng-click 访问事件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com