Gje*_*t G -3 javascript eval dynamic-variables angularjs
我试图弄清楚 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
};
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,当我将值推送到变量数组时, 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);
}
Run Code Online (Sandbox Code Playgroud)
为什么不直接使用括号表示法?https://jsfiddle.net/duoxoq8j/2/
$scope.addRate = function (variable) {
$scope[variable].push({
...
});
$scope[variable + "Rate"] = {
number: undefined,
type: undefined,
from: undefined,
to: undefined,
rate: undefined
};
}
Run Code Online (Sandbox Code Playgroud)
这只是基本的 JavaScript 功能,与 Angular 或范围无关。
| 归档时间: |
|
| 查看次数: |
2007 次 |
| 最近记录: |