I have a use-case, where I want to create a directive which does some processing and returns an array to the controller.
My directive looks something like
angular.module('directives').directive('reuse','testService',function(testService) {
return {
restrict : 'E',
replace : true,
scope :
{ elements: '=elements',
callmethod: '&'
},
controller: testController,
templateUrl: '/abc.html'
};
}]);
The testController
had a method which listens to an event onControllerClick
and calls the reference callmethod
method.
$scope.$on('onControllerClick',function() {
$scope.elements= ['a','b','c'];
var x = $scope.elements; // reason for this is explained below
$scope.callmethod(x);
}
I made a local variable x, because I was not getting the value of elements directly, even when the array is bound bi-directionally.
My invoking of the directive from the html is like
<div>
<reuse elements="elements" callmethod="callmethod(elements)" />
<button type="button" ng-click="broadcastMethod()" />
</div>
The controller of this html looks like
$scope.elements = [];
$scope.broadcastMethod = function() {
$scope.$broadcast('onControllerClick');
};
$scope.callmethod = function(parameterElement) {
console.log(parameterElement);
console.log($scope.elements);
}
The problem that I am facing with this approach is, whenever I click on the button, for the first time, the value of both parameterElement
and $scope.elements
is coming as empty array. But when I click on the button for the second time, Both the values are working as expected. What is it that I am missing on the first time?
P.S : I know the obvious and recommended answer is to use a service, but I am looking for a solution without using them.