Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

angularjs - how to set an interpolated value in angular directive?

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>

where myscopevalue is a value on my controller's scope.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...