如何从子范围中的指令设置角度控制器对象属性值

编程入门 行业动态 更新时间:2024-10-28 17:21:26
本文介绍了如何从子范围中的指令设置角度控制器对象属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-22 06:47:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1017280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   指令   属性   角度   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!