问题描述
限时送ChatGPT账号..我在 ng-repeater 中有一个指令,它应该设置一个范围属性.请看这里的小提琴:http://jsfiddle/paos/CSbRB/
I have have a directive inside an ng-repeater that should set a scope property. Please see the fiddle here: http://jsfiddle/paos/CSbRB/
问题是 scope 属性是作为属性值给出的,如下所示:
The problem is that the scope property is given as an attribute value like this:
<button ng-update1="inputdata.title">click me</button>
该指令应该将范围属性 inputdata.title 设置为某个字符串.这不起作用:
The directive is supposed to set the scope property inputdata.title to some string. This does not work:
app.directive('ngUpdate1', function() {
return function(scope, element, attrs) {
element.bind('click', function() {
scope.$apply(function() {
scope[ attrs.ngUpdate1 ] = "Button 1";
});
});
};
});
然而,直接赋值是有效的:
However, assigning directly works:
scope["inputdata"]["title"] = "Button 1";
你能告诉我如何使用 .来自指令的名称中的符号?
Can you please tell me how I can set a scope property with . notation in its name from a directive?
PS:小提琴使用中继器的原因是因为它使指令在子范围内.当它们在子作用域中时,您不能写入属于基元的作用域属性.这就是为什么我需要一个带有."的对象属性.在名字里.请参阅此处的详细解释:AngularJS 中范围原型/原型继承的细微差别是什么?
PS: The reason the fiddle is using a repeater is because it makes the directives be in child scopes. When they are in a child scope, you can't write to scope properties that are primitives. That's why I need an object property with "." in the name. See the long explanation here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
谢谢
推荐答案
$parse 会解决你的问题.
<button ng-update1="inputdata.title">
app.directive('ngUpdate1', function($parse) {
return function(scope, element, attrs) {
var model = $parse(attrs.ngUpdate1);
console.log(model(scope)); // logs "test"
element.bind('click', function() {
model.assign(scope, "Button 1");
scope.$apply();
});
};
});
小提琴
每当指令不使用隔离范围并且您使用属性指定范围属性,并且您想要修改该值时,请使用 $parse
.
Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to modify the value, use $parse
.
如果不需要修改值,可以用$eval
代替:
If you don't need to modify the value, you can use $eval
instead:
console.log(scope.$eval(attrs.ngUpdate1));
这篇关于如何从子范围中的指令设置角度控制器对象属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论