Passing in a function to be called back on init to a directive, this function is noted by a string attribute which is then parsed and used. The issue is when used, the function binding is no longer attached/bound to the object the function is part of. Here is what I mean (see on plunker)
<html ng-app="plunker">
<head>
<script data-require="[email protected]" src="http://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.container = {
x: null
, setup: function(x){
console.log(this); //this here should be $scope.container, but its window
this.x = x;
}
};
});
app.directive('dir', ['$parse', function($parse) {
return {
restrict: 'E'
, transclude: false
, scope: true
, link: function(scope, element, attrs) {
var callback = attrs.setup
, someCalcVar = 10
;
$parse(callback)(scope)(someCalcVar);
}
};
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<p>container.x == '{{container.x}}'</p>
<dir setup="container.setup"></dir>
</body>
</html>
is there a way to achieve what I want? Perhaps there is a better way to design this but still keep some sort of container for the callback and related variables?
Edit:
A naive win could be to check if the callback has a dot and then bind it manually using func.bind(substr(callback, ...)) ... is there something builtin to angular that would do this? alternatively is there a cleaner approach to all this?
This is not the most elegant solution but you could always just create a function that wraps up calling setup on container:
$scope.callableSetup = function(x) {
$scope.container.setup(x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With