how to set an interpolated value in angular directive?

后端 未结 2 381
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 08:50

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:

相关标签:
2条回答
  • 2020-12-08 09:16

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

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

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

    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.

    0 讨论(0)
  • 2020-12-08 09:25

    Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to change that property's value, I suggest using $parse. (I think the syntax is nicer than $eval's.)

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

    fiddle

    $parse works whether or not the attribute contains a dot.

    0 讨论(0)
提交回复
热议问题