I'm using Angular 1.5. I created a menu which is a component. The menu component accept as attribute a list of jsonObject to create each menuitem.
<comp-menu items="menuitems" ></comp-menu>
A menuitem is a component as well. I would like to add an attribute like "action" which would be a custom function as an evaluated string in data-ng-click... of this kind :
<comp-menuitem data-ng-repeat="item in items" data-ng-click="eval({{item.action}})"></comp-menuitem>
The data can be like in my MainController :
$scope.menuitems = [ { label: 'menuitem 1', action: 'alert("test");'} ... ];
Anyone has an idea to make it work ?
The solution was almost as Scott said. $eval in a component doesn't work, even $rootScope.$eval so I used the function eval() and in the controller I bind my custom function to the $rootScope to be executed in menuitem component.
1) In menuitem.html (menuitem component) -> add data-ng-click="$ctrl.evaluateAction()"
2) In the component controler (menuitem.js) -> add evaluateAction()
3) In menu.html (Menu Component) add the action attribute
4) In the main controller - add the custom function as $rootScope.openDialog()...
5) Add the action attribute data in the JSON
And it works !!!!
ng-click="evaluateAction(item.action)"
where$scope.evaluateAction = eval
. However usingeval
is rarely a good idea, you could use$eval
instead, it only supports Angular expressions and it's also applied against a scope.So you could have
{ action: 'openDialog(item.label)' }
instead and then use it withng-click="evaluateAction(item.action, item)"
where$scope.evaluateAction = (action, item) => $eval(action, item)
.Which still isn't the nicest solution, but at least it keeps your functions in an Angular context and makes it so you need to work with Angular rather than subverting it.