如何在angular指令中设置插值?

Ant*_*ton 17 angularjs angularjs-directive angularjs-scope

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

JS:

app.directive('ngMyDirective', function () {
    return function(scope, element, attrs) {
        console.log(scope.$eval(attrs.ngMyDirective));

        //set the interpolated attrs.ngMyDirective value somehow!!!
    }
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-my-directive="myscopevalue"></div>
Run Code Online (Sandbox Code Playgroud)

哪里myscopevalue是我控制器范围的值.

Mar*_*cok 45

每当指令不使用隔离范围并且您使用属性指定范围属性,并且您想要更改该属性的值时,我建议使用$ parse.(我认为语法比$ eval更好.)

app.directive('ngMyDirective', function ($parse) {
    return function(scope, element, attrs) {
        var model = $parse(attrs.ngMyDirective);
        console.log(model(scope));
        model.assign(scope,'Anton');
        console.log(model(scope));
    }
});
Run Code Online (Sandbox Code Playgroud)

fiddle

$parse 无论属性是否包含点,都可以正常工作.

  • 这绝对是在没有范围隔离的情况下实现'='的正确方法. (3认同)

Mic*_*ley 24

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

scope[attrs.myNgDirective] = 'newValue';
Run Code Online (Sandbox Code Playgroud)

如果属性中的字符串包含一个点(例如myObject.myProperty),则不起作用; 你可以用来$eval做作业:

// like calling  "myscopevalue = 'newValue'"
scope.$eval(attrs.myNgDirective + " = 'newValue'");
Run Code Online (Sandbox Code Playgroud)

[更新:您应该使用$parse而不是$eval.见马克的回答.]

如果您使用隔离范围,则可以使用=注释:

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';
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

你可以看到这样的例子此角/ jQuery的颜色选择器的jsfiddle例如,在分配给scope.color内部的指令自动更新传递的变量在控制器的范围的指令.