I was trying to call a controller function from a directive in order to update a counter inside an hash-map.
After reading a few solutions, I ended up doing this:
'use strict';
var dragDropApp = angular.module('dragDropApp', []);
dragDropApp.controller('DragDropCtrl', function($scope) {
$scope.itemCount = {
'item1' : {
'count' : 0
},
'item2' : {
'count' : 0
},
'item3' : {
'count' : 0
}
};
//this.updateItemCounter = function(itemId) {
// $scope.itemCount[itemId].count++;
//}
$scope.updateItemCounter = function(itemId) {
$scope.itemCount[itemId].count++;
}
}
dragDropApp.directive('droppable', function() {
return {
restrict : 'A',
scope : {
drop : '&', // parent
bin : '=' // bi-directional scope
},
controller : 'DragDropCtrl',
link : function(scope, element, attrs, DragDropCtrl) {
var el = element[0];
el.addEventListener('drop', function(e) {
var item = document.getElementById(
e.dataTransfer.getData('Text')).cloneNode(true);
//DragDropCtrl.updateItemCounter(item.id);
>>>> scope.$parent.updateItemCounter(item.id); <<<<
return false;
}, false);
}
}
});
It works and does what I want, but I don't know if this approach is correct. Is it?
I've also tried to use the controller to access the function updateItemCounter, but the hash-map does not get updated, having the same values every time I call the function.