如何使用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>
菜单项也是一个组件. 我想添加诸如操作"之类的属性,该属性将作为自定义函数,作为这种类型的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");'} ... ];
有人想让它工作吗?
推荐答案
解决方案几乎与Scott所说的一样. $ eval在组件中不起作用,甚至$ rootScope.$ eval也是如此,因此我使用了eval()函数,在控制器中,我将自定义函数绑定到了要在menuitem组件中执行的$ rootScope.
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(菜单组件)中->添加 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屋!