从ng-repeat奇怪内部的ng-click访问事件对象

时间:2016-04-16 03:44:54

标签: javascript jquery angularjs jqlite

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

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

使用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>

1 个答案:

答案 0 :(得分:1)

您正以错误的顺序传递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>