我在AngularJS的世界中相當新,現在我遇到了一個我自己無法解決的問題(我的左手是Google)。通過指令範圍的屬性
我創建了一個指令,如:
.directive('customerTableRow', function() {
return {
restrict: 'E',
scope: {
column: '=column',
key: '@key',
label: '@label',
value: '=value'
},
templateUrl: 'path/to/template.html'
}
})
我用它鑑於這樣的:
<customer-table-row column="column" key="some_key" label="Some Key" value="table.some_key"></customer-table-row>
我用這個另一指令,在這裏我通過「一欄」內和一個來自數據庫的JSON對象轉換成變量「table」,我可以在裏面查看這個變量,如{{column}}
和{{table.id}}
。
這是按預期工作,但我想通過「價值」屬性到我的指令,這樣它就像value: '=table.key'
。我想修改我的指令,以便我只能通過這個key
一次,它將作爲「@key」傳遞到「key」中,並轉換爲「value」,以便它包含「table.key」值,這樣我可以打電話給我的指令,如:
<customer-table-row column="column" key="some_key" label="Some Key"></customer-table-row>
或者相反,如:
<customer-table-row column="column" label="Some Key" value="table.some_key"></customer-table-row>
..和這個指令會從「值」屬性得到「some_key」的指標。
完全可以這樣做,如果是的話,我應該修改什麼?
如果這是一個JavaScript函數,我會做這樣的事情:
var table = {some_key: 'this is table.some_key value'};
function customerTableRow(column, key, label) {
return {
column: column,
key: key,
label: label,
value: eval('table.'+key)
};
}
customerTableRow('some_column', 'some_key', 'Label for row');
,輸出:
Object {
column: "some_column",
key: "some_key",
label: "Label for row",
value: "this is table.some_key value"
}
編輯: 的 「表」,在此value: '=table.key'
可硬編碼,它不需要從父範圍繼承或任何幻想。如果我只能確定一次「鑰匙」,並使用它來傳遞這個指令的「鑰匙」和「數值」參數。