how to set an interpolated value in angular directive?

后端 未结 2 382
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题