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



如何在指令中设置插值值?我可以从下面的代码中读取正确的值,但是我不能设置它。

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是控制器作用域上的值

每当指令不使用隔离作用域,并且您使用属性指定作用域属性,并且您想要更改该属性的值时,我建议使用$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));
    }
});

小提琴

$parse无论属性是否包含点都有效

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

scope[attrs.myNgDirective] = 'newValue';

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

// like calling  "myscopevalue = 'newValue'"
scope.$eval(attrs.myNgDirective + " = 'newValue'");

[更新:你应该用$parse而不是$eval。参考Mark的回答

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

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赋值会自动更新传递给到控制器作用域指令的变量。

最新更新