2015-06-03 101 views
0

我在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'可硬编码,它不需要从父范围继承或任何幻想。如果我只能确定一次“钥匙”,并使用它来传递这个指令的“钥匙”和“数值”参数。

回答

0

好的解决了它。我不得不添加transclude: true,到我的指令,创建一个链接功能,在那里我做了以下内容:

scope.value = (eval('scope.$parent.table.'+scope.key) != '' ? eval('scope.$parent.table.'+scope.key) : ''); 

可能不是这样做的最佳方式,但至少它的一个解决方法。