Is it possible to inject a value into a directive's close scope? I couldn't find any information about this in the angularjs documentation, so I decided to experiment. Does anyone know of a more elegant solution to this issue?
Here is my current approach:
app.directive('injectIntoScopeDirective', function(){
return {
restrict: 'E',
scope: {},
templateUrl: 'inject.tpl.html',
link: function(scope, elem, attrs){
angular.forEach(attrs, function(val, attr){
// variables that need to be injected should have a prefix with the inject keyword
var match = attr.match(/^inject(.*)/);
if( match !== null && match.length > 1 ){
scope['injected' + match[1].toLowerCase()] = val;
}
});
}
}
});
Check out the working plunk
A newer approach using the bindToController property, which is much cleaner.
app.directive('injectIntoScopeDirective', function(){
return {
restrict: 'E',
scope: {},
controller: function(){
},
bindToController: {
inject: '=' // allows us to bind an object to the directive controller
},
controllerAs: 'injectCtrl',
templateUrl: 'inject.tpl.html'
// no linking function needed
}
});
Updated plunk using bindToController property