如何在指令中设置内插值?我可以从以下代码读取正确的值,但是我无法设置它。
JS:
app.directive('ngMyDirective',function () { return function(scope,element,attrs) { console.log(scope.$eval(attrs.ngMyDirective)); //set the interpolated attrs.ngMyDirective value somehow!!! } });
HTML:
<div ng-my-directive="myscopevalue"></div>
其中myscopevalue是我控制器范围的一个值。
如果要在范围上设置值,但不知道属性的名称(提前),则可以使用object [property]语法:
scope[attrs.myNgDirective] = 'newValue';
如果属性中的字符串包含一个点(例如myObject.myProperty),则不起作用;你可以使用$ eval来做一个赋值:
// like calling "myscopevalue = 'newValue'" scope.$eval(attrs.myNgDirective + " = 'newValue'");
[更新:你应该真的使用$ parse而不是$ eval。见Mark’s answer.]
如果您使用的是隔离范围,则可以使用= annotation:
app.directive('ngMyDirective',function () { return { scope: { theValue: '=ngMyDirective' },link: function(scope,attrs) { // will automatically change parent scope value // associated by the variable name given to `attrs.ngMyDirective` scope.theValue = 'newValue'; } } });
您可以在this Angular/jQuery color picker JSFiddle example中看到一个示例,其中分配给指令中的scope.color会自动更新传递给控制器范围的指令的变量。