Reputation: 2053
I have an isolated scope custom directive say
<my_isolate_scope_dir columns="columns" />
And the directive Definition goes something like this.
.directive("myIsolateScopeDir", ["$compile","$templateCache",function($compile,$templateCache){
return {
restrict: 'E',
scope: {
columns: '=',
},
templateUrl: 'customdirective.html',
}
}]);
The question is ,in the directive definition scope:{}
can i define one more scope variable dynamically whose value is coming from the parent scope variable columns
.
The parent controller can be
$scope.columns=[{"name":"x","isLink":true,"onClickFunction":"clickedx"},{"name":"y","isLink":true,"onClickFunction":"clickedy"}]
$scope.clickedx=fucntion()
{
console.log("x is clicked");
}
i want my custom directive scope
definition to be
scope: {
columns: '=',
clickedx: '&', //this is added dynamically to the definition based on the value in columns array
clickedy: '&' //this is added dynamically to the definition based on the value in columns array
},
let me know if this can be achieved in the same way or is there any other simpler way to do this.
Upvotes: 0
Views: 393
Reputation: 5572
You can manually inject the methods into the scope using $parse
.
link: function (scope, element, attrs) {
if (scope.columns) {
scope.columns.forEach(function (column) {
if (column.onClickFunction) {
// column.onClickFunction is a string(eg, clickedx), we need to treat this as a function in scope
var fn = column.onClickFunction + "()";
// get a reference to the function defined in the scope
var getParentMethod = $parse(fn);
// Use of Locals: apart from accessing the properties of the scope, you will be able to pass few properties using locals, which will have the precedence over the properties of scope
// For example if the markup is -- <button on-click="test(arg1, arg2)"
// arg1, arg2 needs to be evaluated in the scope
// As isolateScope breaks the inheritance chain, we need to pass element.scope() to the parser function to access the arg1, arg2 properties from controllers scope
// define a method in the scope with the value of column.onClickFunction (eg, clickedx)
scope[column.onClickFunction] = function (locals) {
// when scope.clicedx is executed execute the method defined in the controller.
return getParentMethod(element.scope(), locals);
}
}
})
}
}
Upvotes: 1