如何设置角度指令的插值? [英] how to set an interpolated value in angular directive?
问题描述
我如何设置指令的插值?我可以阅读从以下code正确的值,但我一直没能进行设定。
How do I set the interpolated value in a directive? I can read the correct value from the following code, but I have not been able to set it.
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
是我的控制器的范围值。
where myscopevalue
is a value on my controller's scope.
推荐答案
如果你想设置的范围值,但不知道该属性(提前),你可以使用的名称对象[属性]
语法
If you want to set a value on the scope but don't know the name of the property (ahead of time), you can use object[property]
syntax:
scope[attrs.myNgDirective] = 'newValue';
如果在属性字符串中包含一个点(例如 myObject.myProperty
),这是不行的;您可以使用 $ EVAL
做一个任务:
If the string in the attribute contains a dot (e.g. myObject.myProperty
), this won't work; you can use $eval
to do an assignment:
// like calling "myscopevalue = 'newValue'"
scope.$eval(attrs.myNgDirective + " = 'newValue'");
[更新:你真的应该使用 $解析
而不是 $ EVAL
。请参见马克的回答]
如果您使用的是分离的范围,你可以使用 =
注释:
If you're using an isolate scope, you can use the =
annotation:
app.directive('ngMyDirective', function () {
return {
scope: {
theValue: '=ngMyDirective'
},
link: function(scope, element, attrs) {
// will automatically change parent scope value
// associated by the variable name given to `attrs.ngMyDirective`
scope.theValue = 'newValue';
}
}
});
您可以看到在这个角/ jQuery的颜色选择器的jsfiddle例如,其中分配给<$ C $的这个例子C> scope.color 里面的指令自动更新通过该变量的到的基于控制器的范围指令。
You can see an example of this in this Angular/jQuery color picker JSFiddle example, where assigning to scope.color
inside the directive automatically updates the variable passed into the directive on the controller's scope.
这篇关于如何设置角度指令的插值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!