如何在角度指令中设置插值? [英] how to set an interpolated value in angular directive?

查看:23
本文介绍了如何在角度指令中设置插值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在指令中设置内插值?我可以从下面的代码中读取正确的值,但我无法设置它.

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.

推荐答案

如果你想在作用域上设置一个值但不知道属性的名称(提前),你可以使用object[property]语法:

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'");

[更新:你真的应该使用 $parse 而不是 $eval.请参阅马克的回答.]

[Update: You should really use $parse instead of $eval. See Mark's answer.]

如果您使用的是隔离作用域,则可以使用 = 注释:

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';
        }
    }
});

您可以在 这个 Angular/jQuery 颜色选择器 JSFiddle 示例中看到这样的示例,其中分配给指令内的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆