http://jsfiddle.net/5mbdgau1/3/
In my fiddle example, I access the event object that is passed in via an ng-click
. It works fine although when accessing it in handling the promise from "OtherService" it is suddenly not there? What is going on here?
Using jQuery works, so this has something to do with Angular jQlite I presume. Also, it breaks inside of ng-repeat
, without that it works. I would like to know why the event object seems to disappear. Thanks.
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>
You are passing the arguments from ng-click
in the wrong order. Change ng-click
from
<div ng-click="vm.foo(item, $event)">{{item}}</div>
to
<div ng-click="vm.foo($event, item)">{{item}}</div>
Your TestService
function first expects an event object.
// 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>