【发布时间】:2017-03-29 19:54:22
【问题描述】:
我试图弄清楚 eval() 在 AngularJS 中是如何工作的,但我似乎无法理解它。
我有以下几点:
$scope.salaryRate, $scope.priceRate = {
number: undefined,
type: undefined,
from: undefined,
to: undefined,
rate: undefined
}
$scope.addRate = function (variable) {
eval('$scope.' + variable).push({
'number': eval('$scope.' + variable + 'Rate').number,
'type': eval('$scope.' + variable + 'Rate').type,
'days': {
'days': eval('$scope.' + variable + 'SelectedDay'),
'daynames': displayDayNames($scope.dayNames, eval('$scope.' + variable + 'SelectedDay'))},
'from': eval('$scope.' + variable + 'Rate').from,
'to': eval('$scope.' + variable + 'Rate').to,
'rate': eval('$scope.' + variable + 'Rate').rate,
'id': eval(variable + 'Number')
});
eval('$scope.' + variable + 'Rate') = {
number: undefined,
type: undefined,
from: undefined,
to: undefined,
rate: undefined
};
}
由于某种原因,当我将值推送到变量数组时,eval 工作正常。但是由于某种原因eval('$scope.' + variable + 'Rate') = 不起作用,我收到错误ReferenceError: Invalid left-hand side in assignment。
我正在尝试使我的函数动态化,以便我可以将它用于多个$scope。如何用 AngularJS 解决这个问题?
此时也恰好失败
function findRowIndex(variable, id){
eval('var ' + variable + 'Rows') = eval('$scope.' + variable);
}
【问题讨论】:
-
你为什么使用 eval?不是个好主意。
-
你到底为什么要这样做?
-
@Phix,我将如何创建一个动态函数,我可以在函数中输入范围名称并使用给定的变量名称修改范围?这个想法是我有多个 $scope 数组,它们使用相同的函数,即 add,除了变量名之外,它们完全相同。
-
@Pytth 正如我所说,我试图避免使用两个完全相同的函数,只是在不同的 $scope 变量集上。
-
@PhyCoMath 我看到你已经有了答案,对你有好处:) 祝你好运
标签: javascript angularjs eval dynamic-variables