我有以下的JavaScript变量:更改代码库
scope.model = {
errors: {
email: ["error1", "error2"],
name: ["error"]
}
}
而且我有一个函数如下:
function (scope, element, attributes) {
if (scope.model.errors) {
if (scope.model.errors[attributes.validator])
// Do something
}
的问题是,这些错误并不总是同一范围变量。
我能有这样的事情:
scope.view = {
newErrors: {
email: ["error1", "error2"],
name: ["error"]
}
在函数内部我知道如何让他们在哪里变量:
function (scope, element, attributes) {
var errors = attributes["validatorErrors"];
// Note: errors is this case "view.newErrors"
// So the following code would become:
if (scope.view.newErrors) {
if (scope.view.newErrors[attributes.validator])
// Do something
}
UPDATE
我已经试过[]之前,但现在我明白了为什么它不工作:
function (scope, element, attributes) {
var errors = attributes["validatorErrors"];
if (scope[errors]) {
if (scope.[errors][attributes.validator])
// Do something
}
如果错误= '错误',它会工作...
如果错误= 'model.errors' 不会。在这种情况下,我需要:
scope['model']['errors'] ...
我该如何解决这个问题?
我不知道你在问什么。 –
你的意思是你想动态获取一个对象的属性?如果是这样,请使用[]符号来访问它,即'scope [errors]',[property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors ) –
当错误=“model.errors”时,它将不起作用。我会工作,如果错误=“错误”。查看我最近的更新。如何解决这个问题? –