Consider the scenario where there are two distinct directives:
angular.module('demo').directive('functional', [function (){
var idempotentMethods = ['idempotentMethod', 'otherIdempotentMethod'];
return {
restrict: 'E',
scope: {
'demoObject': '='
},
templateUrl: 'directive.html',
link: function (scope){
for(var i = 0; i < idempotentMethods.length - 1; i++){
scope[idempotentMethods[i]] = function(){
scope.demoObject[idempotentMethods[i]]();
}
}
}
}
}]);
angular.module('demo').directive('nonFunctional', [function (){
var idempotentMethods = ['idempotentMethod', 'otherIdempotentMethod'];
return {
restrict: 'E',
scope: {
'demoObject': '='
},
templateUrl: 'directive.html',
link: function (scope){
for(var i = 0; i < idempotentMethods.length; i++){
scope[idempotentMethods[i]] = scope.demoObject[idempotentMethods[i]];
}
}
}
}]);
Additionally, there is a factory included in this context:
angular.module('demo').factory('demoFactory', ['$resource', function(resource){
var DemoFactory = resource('demo.json');
angular.extend(DemoFactory.prototype, {
idempotentMethod: function () {
return this.$get();
},
otherIdempotentMethod: function () {
return this.$get();
}
});
return DemoFactory;
}]);
The functional directive faces an issue where invoking the scope.idempotentMethod()
triggers the WRONG Factory method to be executed.
Contrarily, when triggered within the nonFunctional directive, it results in:
TypeError: undefined is not a function
at Scope.angular.extend.idempotentMethod
at $parseFunctionCall
at callback
at Scope.$eval
This anomaly hints at two key points:
1) The function reference binding takes place as expected, but only the final function is being bound.
2) The reference of this
seems erroneous. Upon inspecting this
in the Factory methods, it becomes evident that the non-Functional directive yields Scope while the functional directive gives rise to a Resource.
What could potentially be responsible for these divergent behaviors? Why does the correct function fail to execute and why is there a discrepancy in the binding of the this reference?
A demonstration showcasing this problem can be accessed via the following Plunker link: http://plnkr.co/B52DV0jmSWXc0M6GAamM