如何使用 Angular 1.5 组件将属性评估为字符串,这是一个自定义函数? [英] How to eval an attribute as string which is a custom function using Angular 1.5 component?
问题描述
我使用的是 Angular 1.5.我创建了一个菜单,它是一个组件.菜单组件接受一个 jsonObject 列表作为属性来创建每个菜单项.
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>
菜单项也是一个组件.我想添加一个像action"这样的属性,它是一个自定义函数,作为 data-ng-click... 中的评估字符串:
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>
数据可以像在我的 MainController 中:
The data can be like in my MainController :
$scope.menuitems = [ { label: 'menuitem 1', action: 'alert("test");'} ... ];
有人想过让它发挥作用吗?
Anyone has an idea to make it work ?
推荐答案
解决方案几乎如 Scott 所说.组件中的 $eval 不起作用,甚至 $rootScope.$eval 所以我使用了函数 eval() 并在控制器中我将自定义函数绑定到 $rootScope 以在 menuitem 组件中执行.
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) 在 menuitem.html (menuitem 组件) -> 添加 data-ng-click="$ctrl.evaluateAction()"
1) In menuitem.html (menuitem component) -> add data-ng-click="$ctrl.evaluateAction()"
<button data-ng-click="$ctrl.evaluateAction()"></button>
2) 在组件控制器 (menuitem.js) -> 添加 evaluateAction()
2) In the component controler (menuitem.js) -> add evaluateAction()
function menuitemController($rootScope, $scope, $element, $attrs) {
var ctrl = this;
...
ctrl.evaluateAction = function(){
eval(ctrl.action);
}
}
angular.module('app')
.component('appMenuitem', {
transclude: false,
controller: menuitemController,
bindings :{
label : '@',
...
action: '@'
},
templateUrl: 'angular/components/menuitem/menuitem.html'
});
3) 在 menu.html(菜单组件)中添加 action 属性
3) In menu.html (Menu Component) add the action attribute
<comp-menuitem data-ng-repeat="item in items" action="{{ item.action }}"></comp-menuitem>
4) 在主控制器中 - 添加自定义函数 $rootScope.openDialog()...
4) In the main controller - add the custom function as $rootScope.openDialog()...
angular.module('app')
.controller('MainController', ['$rootScope', '$scope', function($rootScope, $scope){
$rootScope.openDialog = function(key){
if(key === 'open'){
alert("open");
}
};
...
5) 在 JSON 中添加动作属性数据
5) Add the action attribute data in the JSON
{ label : "foo" , action: "$rootScope.openDialog('open')"}
它有效!!!!!!
这篇关于如何使用 Angular 1.5 组件将属性评估为字符串,这是一个自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!